search
HomeBackend DevelopmentPHP TutorialYii Framework Official Guide Series 35 - Extending Yii: Creating Extensions



#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.

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

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


Statement
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
使用Yii框架创建电影网站使用Yii框架创建电影网站Jun 21, 2023 am 09:04 AM

随着互联网的普及以及人们对电影的热爱,电影网站成为了一个受欢迎的网站类型。在创建一个电影网站时,一个好的框架是非常必要的。Yii框架是一个高性能的PHP框架,易于使用且具有出色的性能。在本文中,我们将探讨如何使用Yii框架创建一个电影网站。安装Yii框架在使用Yii框架之前,需要先安装框架。安装Yii框架非常简单,只需要在终端执行以下命令:composer

Yii框架简介:了解Yii的核心概念Yii框架简介:了解Yii的核心概念Jun 21, 2023 am 09:39 AM

Yii框架是一个高性能、高扩展性、高可维护性的PHP开发框架,在开发Web应用程序时具有很高的效率和可靠性。Yii框架的主要优点在于其独特的特性和开发方法,同时还集成了许多实用的工具和功能。Yii框架的核心概念MVC模式Yii采用了MVC(Model-View-Controller)模式,是一种将应用程序分为三个独立部分的模式,即业务逻辑处理模型、用户界面呈

为什么Yii框架比其他框架更好用?为什么Yii框架比其他框架更好用?Jun 21, 2023 am 10:30 AM

Yii框架是一个高性能、可扩展、安全的PHP框架。它是一个优秀的开发工具,能够让开发者快速高效地构建复杂的Web应用程序。以下是几个原因,让Yii框架比其他框架更好用。高性能Yii框架使用了一些先进的技术,例如,延迟加载(lazyloading)和自动加载机制(automaticclassloading),这使得Yii框架的性能高于许多其他框架。它还提

Yii框架中的ViewState:实现数据保护Yii框架中的ViewState:实现数据保护Jun 21, 2023 am 09:02 AM

ViewState是ASP.NET中的一种机制,用于保护页面的隐私数据。而在Yii框架中,ViewState同样也是实现页面数据保护的重要手段。在Web开发中,随着用户界面操作的复杂度增加,前端与后端之间的数据传输也愈发频繁。但是,不可避免的会有恶意用户通过网络抓包等手段截获数据。而未加保护的数据可能含有用户隐私、订单信息、财务数据等重要资料。因此,加密传输

Yii框架中的队列:高效地处理异步操作Yii框架中的队列:高效地处理异步操作Jun 21, 2023 am 10:13 AM

随着互联网的快速发展,应用程序对于处理大量并发请求和任务变得越来越重要。在这样的情况下,处理异步任务是必不可少的,因为这可以使应用程序更加高效,并更好地响应用户请求。Yii框架提供了一个方便的队列组件,使得处理异步操作更加容易和高效。在本篇文章中,我们将探讨Yii框架中队列的使用和优势。什么是队列队列是一种数据结构,用于处理数据的先进先出(FIFO)顺序。队

Yii框架中的分页机制:优化数据展示效果Yii框架中的分页机制:优化数据展示效果Jun 21, 2023 am 08:43 AM

在现今互联网时代,数据的处理和展示对于各种应用而言都是至关重要的。对于一些数据量较大的网站,其展示效果直接影响用户体验,而优秀的分页机制可以使得数据展示更加清晰,提高用户的使用体验。在本文中,我们将介绍Yii框架中的分页机制,并探讨如何通过优化分页机制来改进数据展示效果。Yii框架是一种基于PHP语言的高性能、适用于Web应用的开发框架。它提供

Yii框架中的扩展:使用外部库Yii框架中的扩展:使用外部库Jun 21, 2023 am 10:11 AM

Yii是一款优秀的PHP框架,它提供了很多丰富的功能和组件来加快Web应用程序的开发。其中一个非常重要的特性就是可以方便地使用外部库进行扩展。Yii框架中的扩展可以帮助我们快速完成许多常见的任务,例如操作数据库、缓存数据、发送邮件、验证表单等等。但是有时候,我们需要使用一些其他的PHP类库来完成特定的任务,例如调用第三方API、处理图片、生成PDF文件等等。

Yii框架中的身份认证与授权:保障应用程序的安全性Yii框架中的身份认证与授权:保障应用程序的安全性Jun 21, 2023 am 09:57 AM

在Web应用程序开发领域,身份认证和授权是保障应用程序安全性必不可少的两个环节,而Yii框架提供了完善的身份认证和授权机制,帮助开发者轻松实现这些功能,保障应用程序的安全性。一、身份认证1.1基础认证Yii框架中的基础认证机制采用HTTPBasic认证的方式实现。当用户在浏览器中访问需要认证的页面时,服务器会发送一个401Unauthorized响应,

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

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.