Home  >  Article  >  Backend Development  >  Detailed explanation of Yii framework components and event behavior management, yii behavior management_PHP tutorial

Detailed explanation of Yii framework components and event behavior management, yii behavior management_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:50:31865browse

Detailed explanation of Yii framework components and event behavior management, yii behavior management

This article describes Yii framework components and event behavior management with examples. 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 behavior (behavior).

Component Management

YII is a pure oop framework. Member variables in many classes are protected or private. CComponent uses the magic methods __get() and __set() in PHP to access and set properties, but the role of these methods Far from that. Use __get() to illustrate below

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

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

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

2. Determine whether it starts with on. Events starting with on are generally reserved events in CComponent subclasses. They are used to hang events. Use method_exists($this,$name) to determine whether the name exists in a class. In the instance, 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 is a subclass of CComponent, so use a recursive method to get the method in the behavior. If not, perform step 5

5. Exception thrown: The requested attribute does not exist.

The __get() method can be overloaded in CComponent subclasses. For example, the judgment of obtaining components 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 the attributes we want may not be obtained. 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);
}

Regarding the loading and creation of components, the last YII framework analysis note 1: There is a question in point 3 of the YII execution process: When registering the core components of the framework, so many are loaded at once. Does it 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() through CModule or its descendants (such as CWebApplication) to obtain components, 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 realize the internal call of the component and the external control of the component. 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));
}

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, call the raiseEvent() method in CComponent through the onBeginRequest($event) method to execute the function in the handle or method.

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 the purpose of aspect management and expansion. 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.

PS:The editor here recommends a PHP formatting and beautifying typesetting tool on this website to help you code typesetting in future PHP programming:

PHP code online formatting and beautification tool: http://tools.jb51.net/code/phpformat

Readers who are interested in more Yii-related content can check out the special topics on this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent PHP Development Framework", "Basic Tutorial for Getting Started with Smarty Templates", "php Date and Time" Usage Summary", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1133126.htmlTechArticleDetailed explanation of Yii framework components and event behavior management, yii behavior management This article describes Yii framework components and event behavior management with examples. Share it with everyone for your reference, the details are as follows: Yii is a...
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