Table of Contents
1. Application Component
2. Behavior
4. Action(动作)
5. Filter(过滤器)
6. Controller(控制器)
7. Validator(验证)
8. Console Command(控制台命令)
9. Module(模块)
10. Generic Component(通用组件)
Home Backend Development PHP Tutorial Yii Framework Official Guide Series 35 - Extending Yii: Creating Extensions

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

Feb 15, 2017 am 09:29 AM



#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)!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Yii framework in PHP How to use Yii framework in PHP Jun 27, 2023 pm 07:00 PM

With the rapid development of web applications, modern web development has become an important skill. Many frameworks and tools are available for developing efficient web applications, among which the Yii framework is a very popular framework. Yii is a high-performance, component-based PHP framework that uses the latest design patterns and technologies, provides powerful tools and components, and is ideal for building complex web applications. In this article, we will discuss how to use Yii framework to build web applications. Install Yii framework first,

Unit testing in Yii framework: ensuring code quality Unit testing in Yii framework: ensuring code quality Jun 21, 2023 am 10:57 AM

As software development becomes increasingly complex, ensuring code quality becomes increasingly important. In the Yii framework, unit testing is a very powerful tool that can ensure the correctness and stability of the code. In this article, we will take a deep dive into unit testing in the Yii framework and introduce how to use the Yii framework for unit testing. What is unit testing? Unit testing is a software testing method, usually used to test the correctness of a module, function or method. Unit tests are usually written by developers to ensure the correctness and stability of the code.

RESTful API development in Yii framework RESTful API development in Yii framework Jun 21, 2023 pm 12:34 PM

Yii is a high-performance MVC framework based on PHP. It provides a very rich set of tools and functions to support the rapid and efficient development of web applications. Among them, the RESTful API function of the Yii framework has attracted more and more attention and love from developers, because using the Yii framework can easily build high-performance and easily scalable RESTful interfaces, providing strong support for the development of web applications. . Introduction to RESTfulAPI RESTfulAPI is a

Steps to implement web page caching and page chunking using Yii framework Steps to implement web page caching and page chunking using Yii framework Jul 30, 2023 am 09:22 AM

Steps to implement web page caching and page chunking using the Yii framework Introduction: During the web development process, in order to improve the performance and user experience of the website, it is often necessary to cache and chunk the page. The Yii framework provides powerful caching and layout functions, which can help developers quickly implement web page caching and page chunking. This article will introduce how to use the Yii framework to implement web page caching and page chunking. 1. Turn on web page caching. In the Yii framework, web page caching can be turned on through the configuration file. Open the main configuration file co

Create a game guide website using Yii framework Create a game guide website using Yii framework Jun 21, 2023 pm 01:45 PM

In recent years, with the rapid development of the game industry, more and more players have begun to look for game strategies to help them pass the game. Therefore, creating a game guide website can make it easier for players to obtain game guides, and at the same time, it can also provide players with a better gaming experience. When creating such a website, we can use the Yii framework for development. The Yii framework is a web application development framework based on the PHP programming language. It has the characteristics of high efficiency, security, and strong scalability, and can help us create a game guide more quickly and efficiently.

Encrypt and decrypt sensitive data using Yii framework middleware Encrypt and decrypt sensitive data using Yii framework middleware Jul 28, 2023 pm 07:12 PM

Encrypting and decrypting sensitive data using Yii framework middleware Introduction: In modern Internet applications, privacy and data security are very important issues. To ensure that users' sensitive data is not accessible to unauthorized visitors, we need to encrypt this data. The Yii framework provides us with a simple and effective way to implement the functions of encrypting and decrypting sensitive data. In this article, we’ll cover how to achieve this using the Yii framework’s middleware. Introduction to Yii framework Yii framework is a high-performance PHP framework.

Yii Framework Middleware: Add logging and debugging capabilities to your application Yii Framework Middleware: Add logging and debugging capabilities to your application Jul 28, 2023 pm 08:49 PM

Yii framework middleware: Add logging and debugging capabilities to applications [Introduction] When developing web applications, we usually need to add some additional features to improve the performance and stability of the application. The Yii framework provides the concept of middleware that enables us to perform some additional tasks before and after the application handles the request. This article will introduce how to use the middleware function of the Yii framework to implement logging and debugging functions. [What is middleware] Middleware refers to the processing of requests and responses before and after the application processes the request.

How to use controllers to handle Ajax requests in the Yii framework How to use controllers to handle Ajax requests in the Yii framework Jul 28, 2023 pm 07:37 PM

In the Yii framework, controllers play an important role in processing requests. In addition to handling regular page requests, controllers can also be used to handle Ajax requests. This article will introduce how to handle Ajax requests in the Yii framework and provide code examples. In the Yii framework, processing Ajax requests can be carried out through the following steps: The first step is to create a controller (Controller) class. You can inherit the basic controller class yiiwebCo provided by the Yii framework

See all articles