Yii Framework Official Guide Series 35--extension Yii: Creating an extension

Source: Internet
Author: User
Tags yii



Because the extension means that it is used by third-party developers, some extra effort is needed to create it. The following are some general guidelines:

* Extension is best self-sufficiency. In other words, its external dependencies should be minimal. If the user's extension needs to install additional packages, classes or resource files, this will be a headache. * files that belong to the same extension should be organized in the same directory, with the extension name of the directory name. * Extensions inside the class should use some word letter prefixes to avoid naming conflicts with other extensions. * Extensions should provide detailed installation and API documentation. This reduces the time and effort that other developers spend when using extensions. * Extensions should be made with the appropriate license. If you would like your extension to be used in open source and closed sourcing projects, you may consider using licenses such as BSD, MIT, etc., but not the GPL, as it requires its derivative code to be open source.

Below, we describe how to create a new extension, based on the classification described in overview. These descriptions also apply when you want to create a component part that is primarily used in your own project.

1. Application Component (Application parts)

An application component should implement an interface iapplicationcomponent or inherit capplicationcomponent. The main way to implement this is Iapplicationcomponent::init, where parts perform some initialization work. This method is called when part creation and property values (specified in the application configuration) are assigned.

By default, an application part is created and initialized only when it is first accessed and requires processing. If an application part needs to be created after the application instance is created, it should require the user to list his number in the CApplication::p reload attribute.

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 C Onvenient methods. Child classes mainly need to implement the extra methods this they intend to make available to the components being attach Ed to.

When developing behaviors for CModel and Cactiverecord, one can also extend Cmodelbehavior and Cactiverecordbehavior, resp Ectively. These base classes offer additional features that is 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 would participate in the AR life cycles.

The following code shows an example of a ActiveRecord behavior. When this behavior was attached to a AR object and when the Ar object was being saved by calling save() , it would automatical LY sets the and attributes with the current create_time update_time 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 (Gadget)

The widget should inherit CWidget or its subclasses. A widget should extend from cwidget or it child classes.

The simplest way to build a new gadget is to inherit a ready-made gadget and reload its method or change its default property value. For example, if you want to use a better CSS style for CTabView, you can configure its Ctabview::cssfile property when using a gadget. You can also inherit CTabView as follows, so that when you use gadgets, you no longer need to configure properties.


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 reload the Cwidget::init method and specify the URL of the ctabview::cssfile to our 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 encapsulated into extensions. Because CSS style files are not accessed through the web, we need to publish as an asset resource.

To create a new gadget from scratch, we mainly need to implement two methods: Cwidget::init and Cwidget::run. The first method is called when we $this->beginWidget insert a gadget in the view, and the second method is called when it $this->endWidget is invoked. If we want to capture and process the displayed content between these two method invocations, we can start the 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 method invocations, we can start output Bufferin G in Cwidget::init and retrieve the buffered output with Cwidget::run for further processing.

Gadgets that are used in Web pages, gadgets often include css,javascript or other resource files. We call these files assetsbecause they are together with gadget classes and are usually inaccessible to web users. To make these files accessible through the Web, we need to publish them with Cwebapplication::assetmanager, as shown in the preceding code snippet. Also, if we want to include CSS or JavaScript files on the current page, we need to register with 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 named views in the directory that includes the gadget class files and put all the view files inside. Use the render widget view in the Gadget class $this->render('ViewName') , similar to what we do in the controller.

4. Action (Action)

The action should inherit caction or its subclasses. The main way to implement the action is Iaction::run.

5. Filter (filters)

Filter should inherit Cfilter or its subclasses. The primary method to implement filter is Cfilter::p refilter and Cfilter::p ostfilter. The former is executed before the action, while the latter is behind.


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 Postfil ter ($filterChain)    {        //logic being applied after the action is executed    }}

$filterChainthe type of the parameter is Cfilterchain, which contains information about the action that is currently being filter.

6. Controller (Controllers)

The controller needs to inherit Cextcontroller, not Ccontroller, as an extension. The main reason is that the Ccontroller determines that the controller view file is located application.views.ControllerID under, while the Cextcontroller determines that the view file is in the views directory, and also contains a subdirectory of the Controller class directory. Therefore, it is easy to reassign the controller because its view files and control classes are together.

7. Validator (verification)

Validator need to inherit cvalidator and implement 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 commands)

The console command should inherit the Cconsolecommand and implement the Cconsolecommand::run method. Alternatively, we can overload the cconsolecommand::gethelp to provide some better help commands.


Class MyCommand extends cconsolecommand{public    function Run ($args)    {        //$args gives an array of the COMMAND-L INE arguments for the command    } public    function Gethelp ()    {        return ' usage:how to use this command '; 
  }}

9. Module (modules)

See the Modules section for a module on how to create one.

The general guidelines develop a module that should be independent. The resource files used by the module (such as CSS, JavaScript, pictures) should be distributed with the module. There are also modules that should publish them so that they can be accessed by the Web.

Generic Component (Universal component)

Developing a generic component extension is similar to writing a class. Also, the 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--extension Yii: To create the content of the extension, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.