Table of Contents
Detailed explanation of Yii framework components and event behavior management, yii behavior management
Home Backend Development PHP Tutorial 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

Jul 12, 2016 am 08:50 AM
yii event components

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

Copy after login

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

Copy after login

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

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, 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 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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

Event ID 4660: Object deleted [Fix] Event ID 4660: Object deleted [Fix] Jul 03, 2023 am 08:13 AM

Some of our readers encountered event ID4660. They're often not sure what to do, so we explain it in this guide. Event ID 4660 is usually logged when an object is deleted, so we will also explore some practical ways to fix it on your computer. What is event ID4660? Event ID 4660 is related to objects in Active Directory and will be triggered by any of the following factors: Object Deletion – A security event with Event ID 4660 is logged whenever an object is deleted from Active Directory. Manual changes – Event ID 4660 may be generated when a user or administrator manually changes the permissions of an object. This can happen when changing permission settings, modifying access levels, or adding or removing people or groups

How to implement calendar component using Vue? How to implement calendar component using Vue? Jun 25, 2023 pm 01:28 PM

Vue is a very popular front-end framework. It provides many tools and functions, such as componentization, data binding, event handling, etc., which can help developers build efficient, flexible and easy-to-maintain Web applications. In this article, I will introduce how to implement a calendar component using Vue. 1. Requirements analysis First, we need to analyze the requirements of this calendar component. A basic calendar should have the following functions: display the calendar page of the current month; support switching to the previous month or next month; support clicking on a certain day,

Get upcoming calendar events on your iPhone lock screen Get upcoming calendar events on your iPhone lock screen Dec 01, 2023 pm 02:21 PM

On iPhones running iOS 16 or later, you can display upcoming calendar events directly on the lock screen. Read on to find out how it's done. Thanks to watch face complications, many Apple Watch users are used to being able to glance at their wrist to see the next upcoming calendar event. With the advent of iOS16 and lock screen widgets, you can view the same calendar event information directly on your iPhone without even unlocking the device. The Calendar Lock Screen widget comes in two flavors, allowing you to track the time of the next upcoming event, or use a larger widget that displays event names and their times. To start adding widgets, unlock your iPhone using Face ID or Touch ID, press and hold

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

Vue component practice: paging component development Vue component practice: paging component development Nov 24, 2023 am 08:56 AM

Vue component practice: Introduction to paging component development In web applications, the paging function is an essential component. A good paging component should be simple and clear in presentation, rich in functions, and easy to integrate and use. In this article, we will introduce how to use the Vue.js framework to develop a highly customizable paging component. We will explain in detail how to develop using Vue components through code examples. Technology stack Vue.js2.xJavaScript (ES6) HTML5 and CSS3 development environment

In JavaScript, what is the purpose of the 'oninput' event? In JavaScript, what is the purpose of the 'oninput' event? Aug 26, 2023 pm 03:17 PM

When a value is added to the input box, the oninput event occurs. You can try running the following code to understand how to implement oninput events in JavaScript - Example<!DOCTYPEhtml><html> <body> <p>Writebelow:</p> <inputtype="text&quot

See all articles