Yii Framework official guide series 35-extension Yii: Create extension

Source: Internet
Author: User
Because the extension is used by third-party developers, some extra efforts are required to create it. Below are some general guiding principles: * expansion should be self-contained. That is to say, its external dependencies should be the least. If your extension...



Because the extension is used by third-party developers, some extra efforts are required to create it. The following are general guiding principles:

* Expansion should be self-contained. That is to say, its external dependencies should be the least. If you need to install additional software packages, classes, or resource files for your extension, this will be a headache. * Files belonging to the same extension should be organized in the same directory, and the directory name should be extended. * Classes in the extension should use certain word/letter prefixes to avoid conflicts with other extension names. * The extension should provide detailed installation and API documentation. This reduces the time and effort spent by other developers when using extensions. * The extension should be licensed as appropriate. If you want your extensions to be used in open-source and closed-source projects, you can consider using licenses, such as BSD and MIT, but not GPL, because it requires the derived code to be open-source.

Next, we will describe how to create a new extension based on the categories described in overview. These descriptions also apply when you create a component that is mainly used for your project.

1. Application Component (Application components)

An application component should implement the IApplicationComponent interface or inherit the CApplicationComponent. The main implementation method is IApplicationComponent: init. the component performs some initialization work here. This method is called after the component creation and attribute values (specified in application configuration) are assigned values.

By default, an application part is created and initialized only when it is requested during its first access. If an application part needs to be created after the application instance is created, it requires the user to list its number in the attributes 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 convenient methods. child classes mainly need to implement the extra methods that they intend to make available to the components being attached.

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 callingsave(), It will automatically setscreate_timeAndupdate_timeAttributes 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. widgets)

Widgets should inherit from CWidget or its subclass. A widget shoshould extend from CWidget or its child classes.

The simplest way to create a new tool is to inherit a ready-made tool and reload its method or change its default attribute value. For example, if you want to use a better CSS style for CTabView, you can configure its CTabView: cssFile attribute when using a small tool. You can also inherit the CTabView as follows, so that you do not need to configure attributes when using gadgets.


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 section, we reload the CWidget: init method and specify the CTabView: cssFile URL to our new default CSS style if this attribute is not set. The new CSS style file andMyTabViewClass files are placed in the same directory so that they can be encapsulated into extensions. Since CSS style files are not accessed through Web, we need to publish them as an asset resource.

To create a new tool from scratch, we mainly need to implement two methods: CWidget: init and CWidget: run. The first method is when we use$this->beginWidgetThe second method is called when you insert a small tool.$this->endWidgetCalled when called. If we want to capture and process the displayed content between the two method calls, we can start to output buffering in CWidget: init and reclaim the buffer 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.

Small tools used in web pages often include CSS, Javascript, or other resource files. We call these filesAssetsBecause they are associated with small tool classes and are usually inaccessible to Web users. To make these files accessible through the Web, we need to use CWebApplication: assetManager to publish them, as shown in the code snippet above. In addition, if we want to include CSS or JavaScript files on the current webpage, we need to register using CClientScript:


class MyWidget extends CWidget{    protected function registerClientScript()    {        // ...publish CSS or JavaScript file here...        $cs=Yii::app()->clientScript;        $cs->registerCssFile($cssFile);        $cs->registerScriptFile($jsFile);    }}

Gadgets may also have their own view files. If so, create a directory nameviewsStore all the view files in the directory that includes the small tool files. Use in a small tool class$this->render('ViewName')To render the rendering tool view, similar to what we do in the controller.

4. Action)

Action should inherit CAction or its subclass. The main method to implement action is IAction: run.

5. Filter)

Filters should inherit from CFilter or its subclass. The main methods to implement the filter are CFilter: preFilter and CFilter: postFilter. The former is executed before the action, and the latter is later.


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    }}

Parameters$filterChainCFilterChain contains information about the action Currently filtered.

6. Controller)

To be extended, the controller must inherit CExtController instead of CController. The main reason is that CController determines that the controller view file is located inapplication.views.ControllerIDAnd CExtController determines that the view file isviewsDirectory is also a sub-directory that contains the controller class directory. Therefore, it is easy to re-allocate the controller because its view file and control class are together.

7. Validator (verification)

Validator must inherit from CValidator and implement the CValidator: validateAttribute method.


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)

The console command should inherit the CConsoleCommand and implement the CConsoleCommand: run method. Alternatively, we can overload CConsoleCommand: getHelp to provide better help commands.


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)

See how to create a module in the modules section.

Generally, a module should be developed based on the guidelines, which should be independent. The resource files used by the module (such as CSS, JavaScript, and images) should be distributed together with the module. Other modules should publish them so that they can be accessed on the Web.

10. Generic Component (common Component)

Developing a universal component extension is similar to writing a class. Also, this component should be self-contained so that it can be easily used by other developers.

The above is the Yii Framework official guide series 35-extended Yii: create extended content. For more information, see The PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.