


#Since the extension is meant for use by third-party developers, some extra effort is required to create it. Here are some general guidelines:
*Extensions are best self-sufficient. In other words, its external dependencies should be minimal. If the user's extension requires the installation of additional packages, classes or resource files, this will be a headache. *Files belonging to the same extension should be organized in the same directory, and the directory name uses the extension name. *Classes inside extensions should use some word letter prefixes to avoid naming conflicts with other extensions. *Extensions should provide detailed installation and API documentation. This will reduce the time and effort spent by other developers using the extension. *Extensions should be used with appropriate permissions. If you want your extension to be used in both open source and closed source projects, you may consider using a license such as BSD, MIT, etc., but not GPL, as it requires the code derived from it to be open source.
In the following, we describe how to create a new extension according to the categories described in the overview. These descriptions also apply when you want to create a component that will be used primarily in your own projects.
1. Application Component
An application component should implement the interface IApplicationComponent or inherit CApplicationComponent. The main method that needs to be implemented is IApplicationComponent::init, where the component performs some initialization work. This method is called after the widget is created and the property values (specified in the application configuration) are assigned.
By default, an application component is created and initialized only when it is first accessed during request processing. If an application component needs to be created after the application instance is created, it should require the user to list his number in the properties of CApplication::preload.
2. Behavior
To create a behavior, one must implement the IBehavior interface. For convenience, Yii provides a base class CBehavior that already implements this interface and provides some additional convenience methods. Child classes mainly need to implement the extra methods that they intend to make available to the components being attached to.
When developing behaviors for CModel and CActiveRecord, one can also extend CModelBehavior and CActiveRecordBehavior, respectively. These base classes offer additional features that are specifically made for CModel and CActiveRecord. For example, the CActiveRecordBehavior class implements a set of methods to respond to the life cycle events raised in an ActiveRecord object. A child class can thus override these methods to put in customized code which will participate in the AR life cycles.
The following code shows an example of an ActiveRecord behavior. When this behavior is attached to an AR object and when the AR object is being saved by calling save()
, it will automatically sets the create_time
and update_time
attributes with the current timestamp.
##
class TimestampBehavior extends CActiveRecordBehavior { public function beforeSave($event) { if($this->owner->isNewRecord) $this->owner->create_time=time(); else $this->owner->update_time=time(); } }3. Widget (small tool) Widget should inherit CWidget or its subclass. A widget should extend from CWidget or its child classes.The easiest way to create a new widget is to inherit an existing widget and override its methods or change its default property values. For example, if you want to use better CSS styling for a CTabView, you can configure its CTabView::cssFile property when using the gadget. You can also inherit CTabView as follows, so that you no longer need to configure properties when using the gadget.
class MyTabView extends CTabView { public function init() { if($this->cssFile===null) { $file=dirname(__FILE__).DIRECTORY_SEPARATOR.'tabview.css'; $this->cssFile=Yii::app()->getAssetManager()->publish($file); } parent::init(); } }In the above, we overload the CWidget::init method and specify the URL of CTabView::cssFile to our The new default CSS style if this property is not set. We put the new CSS style files and
MyTabView class files in the same directory so that they can be packaged as extensions. Since the CSS style files are not accessible from the web, we need to publish them as an asset resource.
$this->beginWidget, and the second method is called when
$this->endWidget When called. If we want to capture and process the displayed content between these two method calls, we can start output buffering in CWidget::init and recycle the buffered output in CWidget::run for further processing. If we want to capture and process the content displayed between these two method invocations, we can start output buffering in CWidget::init and retrieve the buffered output in CWidget::run for further processing.
在网页中使用的小工具,小工具往往包括CSS,Javascript或其他资源文件。我们叫这些文件assets,因为他们和小工具类在一起,而且通常Web用户无法访问。为了使这些档案通过Web访问,我们需要用CWebApplication::assetManager发布他们,例如上述代码段所示。此外,如果我们想包括CSS或JavaScript文件在当前的网页,我们需要使用CClientScript注册 :
class MyWidget extends CWidget { protected function registerClientScript() { // ...publish CSS or JavaScript file here... $cs=Yii::app()->clientScript; $cs->registerCssFile($cssFile); $cs->registerScriptFile($jsFile); } }
小工具也可能有自己的视图文件。如果是这样,创建一个目录命名views
在包括小工具类文件的目录下,并把所有的视图文件放里面。在小工具类中使用$this->render('ViewName')
来render渲染小工具视图,类似于我们在控制器里做。
4. Action(动作)
action应继承CAction或者其子类。action要实现的主要方法是IAction::run 。
5. Filter(过滤器)
filter应继承CFilter 或者其子类。filter要实现的主要方法是CFilter::preFilter和CFilter::postFilter。前者是在action之前被执行,而后者是在之后。
class MyFilter extends CFilter { protected function preFilter($filterChain) { // logic being applied before the action is executed return true; // false if the action should not be executed } protected function postFilter($filterChain) { // logic being applied after the action is executed } }
参数$filterChain
的类型是CFilterChain,其包含当前被filter的action的相关信息。
6. Controller(控制器)
controller要作为扩展需继承CExtController,而不是 CController。主要的原因是因为CController 认定控制器视图文件位于application.views.ControllerID
下,而CExtController认定视图文件在views
目录下,也是包含控制器类目录的一个子目录。因此,很容易重新分配控制器,因为它的视图文件和控制类是在一起的。
7. Validator(验证)
Validator需继承CValidator和实现CValidator::validateAttribute方法。
class MyValidator extends CValidator { protected function validateAttribute($model,$attribute) { $value=$model->$attribute; if($value has error) $model->addError($attribute,$errorMessage); } }
8. Console Command(控制台命令)
console command 应继承CConsoleCommand和实现CConsoleCommand::run方法。 或者,我们可以重载CConsoleCommand::getHelp来提供 一些更好的有关帮助命令。
class MyCommand extends CConsoleCommand { public function run($args) { // $args gives an array of the command-line arguments for this command } public function getHelp() { return 'Usage: how to use this command'; } }
9. Module(模块)
请参阅modules一节中关于就如何创建一个模块。
一般准则制订一个模块,它应该是独立的。模块所使用的资源文件(如CSS , JavaScript ,图片),应该和模块一起分发。还有模块应发布它们,以便可以Web访问它们 。
10. Generic Component(通用组件)
开发一个通用组件扩展类似写一个类。还有,该组件还应该自足,以便它可以很容易地被其他开发者使用。
以上就是Yii框架官方指南系列35——扩展Yii:创建扩展的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
