Home Backend Development PHP Tutorial Analysis of Yii framework components and event behavior management

Analysis of Yii framework components and event behavior management

Jun 19, 2018 pm 02:19 PM
yii Component management

This article mainly introduces Yii framework components and event behavior management, and analyzes in detail the principles and usage techniques of Yii framework component management and behavior management. Friends in need can refer to it

This article describes the examples of Yii Framework components and event behavior management. Share it with everyone for your reference, the details are as follows:

Yii is a component-based, high-performance PHP framework for developing large-scale web applications. CComponent is almost the base class of all classes. It controls the management of components and events. Its methods and properties are as follows. The private variable $_e data stores events (evnet, called hook in some places), and the $_m array stores behaviors (behavior).

Component Management

YII is a pure oop framework, many member variables in classes are protected or private, CComponent The magic methods __get() and __set() in PHP are used to access and set properties, but the functions of these methods are far beyond that. The following uses __get() to illustrate

public function __get($name)
{
  $getter='get'.$name;
  if(method_exists($this,$getter))
    return $this->$getter();
  else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  {
    // duplicating getEventHandlers() here for performance
    $name=strtolower($name);
    if(!isset($this->_e[$name]))
      $this->_e[$name]=new CList;
    return $this->_e[$name];
  }
  else if(isset($this->_m[$name]))
    return $this->_m[$name];
  else if(is_array($this->_m))
  {
    foreach($this->_m as $object)
    {
      if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
        return $object->$name;
    }
  }
  throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
    array('{class}'=>get_class($this), '{property}'=>$name)));
}
Copy after login

When the CComponent or its subclass object instance $obj->name, the __get($name) method :

1. First determine whether there is a getName() method in the instance. If so, return it. If not, perform step 2.

2. Determine whether it starts with on. Generally, they are events reserved in CComponent subclasses. They are used to hang on events. Use method_exists($this,$name) to determine whether the name exists in an instance of the class. If it exists, return the event, otherwise execute step 3

3. If name exists in the behavior array, return the changed behavior. If it does not exist, perform step 4.

4. Traverse the behavior array. The behavior in the array is an instance of the CBehavior subclass, and CBehavior It is a subclass of CComponent again, so use a recursive method to obtain the method in the behavior. If not, perform step 5

5. Throw an exception: the requested attribute does not exist.

The __get() method can be overloaded in the CComponent subclass. For example, the judgment of obtaining the component is added to CModule. This brings up a problem. It is best not to have the same name for attributes and components, because the program will load the component first and may not get the attributes we want. If the names must be the same, getters must be used to obtain the attributes.

public function __get($name)
{
  if($this->hasComponent($name))
    return $this->getComponent($name);
  else
    return parent::__get($name);
}
Copy after login

Regarding the loading and creation of components, the previous YII framework analysis notes 1: There is a question in the third point of the YII execution process: the registration framework core Does loading so many components at once affect performance? Actually no. When registering, you just save the component and its corresponding configuration in the form of key-value pairs in an array (except for preloaded ones). When it is used, you can create the component as above, which will be done through createComponent( in YIIBase ) method is created and initialized. When calling __get() or getComponent() to obtain a component through CModule or its descendant class (such as CWebApplication), CModule establishes an object pool through the $_components array to ensure that each component is only instantiated once in a request.

Event Behavior Management

Events are equivalent to extensions or plug-ins to a component. The hooks reserved in the component are used to implement internal calls to the outside of the component and partial control of the component from the outside. . In the CComponent subclass, you can define methods starting with on as events, similar to onclick, onchange, etc. in js. In fact, the principles are similar. All events are subclasses of CEvent in the same file as CComponent.

/**
* Raised right BEFORE the application processes the request.
* @param CEvent $event the event parameter
*/
public function onBeginRequest($event)
{
  $this->raiseEvent('onBeginRequest',$event);
}
/**
* Runs the application.
* This method loads static application components. Derived classes usually overrides this
* method to do more application-specific tasks.
* Remember to call the parent implementation so that static application components are loaded.
*/
public function run()
{
  if($this->hasEventHandler('onBeginRequest'))
    $this->onBeginRequest(new CEvent($this));
  $this->processRequest();
  if($this->hasEventHandler('onEndRequest'))
    $this->onEndRequest(new CEvent($this));
}
Copy after login

For example, when calling the run() method in CApplication, before processing the request, first determine whether the handle of the onBeginRequest event is passed externally. If so, pass onBeginRequest($event ) method calls the raiseEvent() method in CComponent to execute the function or method in the handle.

Behavior is an upgraded version of events, and all behaviors are subclasses of CBeavior. Analyzing step 4 of the above __get() method analysis, we can see that the role of behavior is to completely extend the characteristics of the component, which can be properties, methods, events and even behaviors, which makes program development more flexible.

Another function of behavior is to put similar event handles together. When the behavior executes the attach() method, it will bind the event handle returned in the events() method. This achieves aspect management and expansion. the goal of. For example, CModelBehavior collects model-related events to facilitate the reuse of its subclasses. We can inherit it when we need to add behaviors to the model.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About the usage of yii paging component

About the usage of rules class validator in Yii data model

The above is the detailed content of Analysis of Yii framework components and event behavior management. For more information, please follow other related articles on the PHP Chinese website!

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 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 PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

Yii2 Programming Guide: How to run Cron service Yii2 Programming Guide: How to run Cron service Sep 01, 2023 pm 11:21 PM

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

PHP development: Use Yii2 and GrapeJS to implement back-end CMS and front-end visual editing PHP development: Use Yii2 and GrapeJS to implement back-end CMS and front-end visual editing Jun 15, 2023 pm 11:48 PM

In modern software development, building a powerful content management system (CMS) is not an easy task. Not only do developers need to have extensive skills and experience, but they also need to use the most advanced technologies and tools to optimize their functionality and performance. This article introduces how to use Yii2 and GrapeJS, two popular open source software, to implement back-end CMS and front-end visual editing. Yii2 is a popular PHPWeb framework that provides rich tools and components to quickly build

How to convert yii objects into arrays or directly output to json format How to convert yii objects into arrays or directly output to json format Jan 08, 2021 am 10:13 AM

Yii framework: This article introduces Yii's method of converting objects into arrays or directly outputting them into json format. It has certain reference value and I hope it can help you.

See all articles