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

Analysis of Yii framework components and event behavior management

不言
Release: 2023-04-01 13:44:01
Original
2425 people have browsed it

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!

Related labels:
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