Yii Framework Official Guide Series 35 - Extending Yii: Creating Extensions

黄舟
Release: 2023-03-05 18:30:01
Original
1167 people have browsed it



#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();
    }
}
Copy after login

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();
    }
}
Copy after login

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.

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 insert a widget in the view using

$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);
    }
}
Copy after login

小工具也可能有自己的视图文件。如果是这样,创建一个目录命名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
    }
}
Copy after login

参数$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);
    }
}
Copy after login

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';
    }
}
Copy after login

9. Module(模块)

请参阅modules一节中关于就如何创建一个模块。

一般准则制订一个模块,它应该是独立的。模块所使用的资源文件(如CSS , JavaScript ,图片),应该和模块一起分发。还有模块应发布它们,以便可以Web访问它们 。

10. Generic Component(通用组件)

开发一个通用组件扩展类似写一个类。还有,该组件还应该自足,以便它可以很容易地被其他开发者使用。

以上就是Yii框架官方指南系列35——扩展Yii:创建扩展的内容,更多相关内容请关注PHP中文网(www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template