Component and event behavior management

Source: Internet
Author: User

Yii is a high-performance PHP framework based on components for developing large web applications. CComponent is the base class of almost all classes. It controls the management of components and events. Its methods and attributes are as follows: private variable $ _ e Data Storage event (evnet, in some cases, it is called Hook) and the $ _ m array storage behavior (behavior ).



Component Management

Yii is a pure OOP framework. member variables in many classes are protected or private. In cComponent, use the magic method _ Get () ,__ set () in PHP () to access and set properties, but these methods do not. The following uses _ Get () to describe

[PHP]View plaincopyprint?

  1. Public Function _ Get ($ name)

  2. {

  3. $ Getter = 'get'. $ name;

  4. If (method_exists ($ this, $ getter ))

  5. Return $ this-> $ getter ();

  6. Else if (strncasecmp ($ name, 'on', 2) ===0 & method_exists ($ this, $ name ))

  7. {

  8. // Duplicating geteventhandlers () HERE FOR PERFORMANCE

  9. $ Name = strtolower ($ name );

  10. If (! Isset ($ this-> _ e [$ name])

  11. $ This-> _ e [$ name] = new clist;

  12. Return $ this-> _ e [$ name];

  13. }

  14. Else if (isset ($ this-> _ m [$ name])

  15. Return $ this-> _ m [$ name];

  16. Else if (is_array ($ this-> _ m ))

  17. {

  18. Foreach ($ this-> _ m as $ object)

  19. {

  20. If ($ object-> getenabled () & (property_exists ($ object, $ name) | $ object-> cangetproperty ($ name )))

  21. Return $ object-> $ name;

  22. }

  23. }

  24. Throw new cexception (yii: T ('yii', 'Property "{class}. {property}" is not defined .',

  25. Array ('{class}' => get_class ($ this), '{property}' => $ name )));

  26. }

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 cComponent or its subclass object instance $ obj-> name, __get ($ name) method:
1. First, determine whether the getname () method exists in the instance. If yes, return. If no step 2nd is executed
2. Determine whether it starts with "ON". Generally, events starting with "on" are reserved in the cComponent subclass. Use and attach events through method_exists ($ this, $ name) checks whether the name exists in the instance of the class. If yes, the system returns an event. Otherwise, the system executes step 1.
3. If the name exists in the behavior array, the system returns the change behavior. If the name does not exist, perform step 1.
4. traverse the behavior array. The behavior in the array is the instance of the cbehavior subclass, And the cbehavior is the subclass of cComponent. Therefore, use recursive methods to obtain the method in the behavior. If not, perform step 1.
5. Throw an exception: the request property does not exist.

You can overload the _ Get () method in the cComponent subclass. For example, you can add the judgment to the cmodule to obtain the component. Note that the attribute and component name should not be duplicated, because the program will give priority to loading the component and may not obtain the desired attribute. If the attribute must be duplicated, you must use getter to obtain the attributes.

[PHP]View plaincopyprint?

  1. Public Function _ Get ($ name)

  2. {

  3. If ($ this-> hascomponent ($ name ))

  4. Return $ this-> getcomponent ($ name );

  5. Else

  6. Return parent ::__ get ($ name );

  7. }

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

About the component loading and creation, I have a question in the previous yii Framework Analysis Note 1: Point 3rd in the yii Execution Process: When I register the core components of the framework, I suddenly load so many components. Does this affect the performance? Actually, no. During registration, only the components and their corresponding configurations are saved in the array in the form of key-value pairs (except for pre-loading ), the component will be created and initialized by using the createcomponent () method in yiibase. When _ Get () or getcomponent () is called by cmodule or its child classes (such as cwebapplication) to obtain a component, cmodule creates an object pool through the $ _ components array, make sure that each component is instantiated only once in one request.


Event behavior management

An event is equivalent to an extension or plug-in for a component. The hooks reserved in the component are used to implement internal call of the component and external control of the component. In the cComponent subclass, you can define methods starting with on as events, similar to onclick and onchange in JS. In fact, the principle is similar. All events are subclasses of cevent in the same file as cComponent.

[PHP]View plaincopyprint?

  1. /**

  2. * Raised right before the application processes the request.

  3. * @ Param cevent $ event the event Parameter

  4. */

  5. Public Function onbeginrequest ($ event)

  6. {

  7. $ This-> raiseevent ('onininrequest', $ event );

  8. }

  9. /**

  10. * Runs the application.

  11. * This method loads static application components. Derived classes usually overrides this

  12. * Method to do more application-specific tasks.

  13. * Remember to call the parent implementation so that static application components are loaded.

  14. */

  15. Public Function run ()

  16. {

  17. If ($ this-> haseventhandler ('onininrequest '))

  18. $ This-> onbeginrequest (New cevent ($ this ));

  19. $ This-> processrequest ();

  20. If ($ this-> haseventhandler ('onendrequest '))

  21. $ This-> onendrequest (New cevent ($ this ));

  22. }

/*** 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, in capplication, call the run () method to determine whether to pass the onbeginrequest event handle externally before processing the request. If yes, use the onbeginrequest ($ event) method to call raiseevent () in cComponent () method.

Action is an upgraded version of the event, and all actions are subclasses of cbehavior. Analyze the above step 1 of the _ Get () method analysis, we can see that the role of behavior is to fully expand the features of the component, which can be attributes, methods, events, and even behaviors, this makes program development more flexible.

Another function of behavior is to put the similar event handle together. When the attach () method is executed, the event handle returned by the events () method is bound, in this way, management and expansion are achieved. For example, cmodelbehavior aggregates model-related events to facilitate the reuse of child classes. When we need to add behavior for the model, we can inherit it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.