In-depth explanation of attributes in PHP Yii Framework)

Source: Internet
Author: User
Tags hasproperty
This article mainly introduces the Property in the PHP Yii Framework, and describes in detail the steps for implementing the Property. if you need it, refer to the following in PHP, class member variables are also called properties ). They are part of the class definition and are used to represent the status of an instance (that is, different instances of the partition classification ). In practice, we often want to use a slightly special method to read and write attributes. For example, if you need to perform trim operations on the label attribute every time, you can use the following code:

$object->label = trim($label);

The disadvantage of the above code is that the trim () function must be called again as long as the label attribute is modified. If you need to process the label attribute in other ways in the future, such as uppercase letters, you have to modify all codes that assign values to the label attribute. Repeated code may cause bugs. this practice should be avoided as much as possible.

To solve this problem, Yii introduces a base class named yii \ base \ Object. it supports defining attributes based on the getter and setter methods in the class. To support this feature, you only need to inherit yii \ base \ Object or its subclass.

Supplement: almost every core class of the Yii Framework inherits from yii \ base \ Object or its subclass. This means that as long as you see the getter or setter method in the core class, you can call it like calling the property.
The getter method is a method whose name starts with get, while the setter method name starts with set. The get or set attributes are defined in the method name. As shown in the following code, the getter method getLabel () and setter method setLabel () operate on the label attribute ,:

namespace app\components;use yii\base\Object;class Foo extend Object{  private $_label;  public function getLabel()  {    return $this->_label;  }  public function setLabel($value)  {    $this->_label = trim($value);  }}

(For details, the getter and setter methods create an attribute named label. In this example, it points to a private internal attribute _ label .)

The property usage defined by getter/setter is the same as that defined by class member variables. The main difference between the two is: when this attribute is read, the corresponding getter method will be called; when the attribute is assigned, the corresponding setter method will be called. For example:

// Equivalent to $ label = $ object-> getLabel (); $ label = $ object-> label; // equivalent to $ object-> setLabel ('ABC '); $ object-> label = 'abc ';

Only the read-only attribute is defined for getter without setter. The yii \ base \ InvalidCallException (invalid call) exception will be caused by an attempt to assign such an attribute. Similarly, only the setter method is used, and the attribute defined by the getter method is used to write only the attribute. An exception is triggered when you try to read this attribute. There are almost no cases of using write-only attributes.

Attributes defined by getter and setter also have some special rules and restrictions:

These attributes are case-insensitive. For example, $ object-> label and $ object-> Label are the same attribute. Because PHP method names are case insensitive.
If the property names and class member variables are the same, the latter prevails. For example, assume that the above Foo class has a label member variable, assign a value to $ object-> label = 'abc', and assign it to the member variable instead of the setter setLabel () method.
This type of attribute does not support visibility (access restrictions ). The getter and setter methods of the property are defined as public, protected, or private, which has no effect on the visibility of the property.
The getter and setter methods of these attributes can only be defined as non-static. if they are defined as static methods, they will not be processed in the same way.
Back to the problem mentioned at the beginning, instead of calling the trim () function everywhere, we only need to call it once in the setter setLabel () method. If the new requirement for changing the initial character of a label to uppercase is met, we only need to modify the setLabel () method without any additional code.

Steps for implementing attributes

We know that when we read and write a nonexistent member variable of an object, _ get () _ set () will be automatically called. Yii uses this to provide support for attributes. From the code above, we can see that if you access an object's property, Yii will call the function named get property name. For example, SomeObject-> Foo will automatically call SomeObject-> getFoo (). If you modify a property, the corresponding setter function is called. For example, SomeObject-> Foo = $ someValue will automatically call SomeObject-> setFoo ($ someValue ).

Therefore, to implement attributes, there are usually three steps:

  • Inherited from yii \ base \ Object.
  • Declare a private member variable used to save the property.
  • Provides getter or setter functions, or both, for accessing and modifying the private member variables mentioned above. If only getter is provided, this attribute is read-only. if only setter is provided, it is write-only.

The following Post class implements a readable and writable attribute title:

Class Post extends yii \ base \ Object // Step 1: inherit from yii \ base \ Object {private $ _ title; // Step 2: declare a private member variable public function getTitle () // Step 3: provide getter and setter {return $ this-> _ title;} public function setTitle ($ value) {$ this->_title = trim ($ value );}}

Theoretically, writing private $ _ title into public $ title can also read and write $ post-> title. But this is not a good habit for the following reasons:

Class encapsulation is lost. Generally, member variables that are invisible to the outside are good programming habits. You may not see it from here, but if one day you don't want the user to modify the title, how do you change it? How can I ensure that the title is not directly modified in the code? If setter is provided, you only need to delete the setter. once a title is written, an exception is thrown. If you use the public $ title method, you can change it to private $ title to troubleshoot write exceptions, but the read is also disabled.
You want to remove spaces for writing titles. To use the setter method, you only need to call trim () in this place like the code snippet above. However, if you use the public $ title method, trim () is required for each write statement (). Can you ensure there is no omission?
Therefore, using public $ title is just a quick start and looks simple, but it will be a headache for future changes. It is simply a nightmare. This is the significance of software engineering. through some methods, the code is easy to maintain and modify. It seems that there is no need for a moment, but in fact, a friend who has suffered a loss or is forced by the customer boss to modify the code written by a programmer and greet his loved ones will think this is very necessary.

However, there is no absolute thing in the world. Because _ get () and _ set () are called only when all member variables are traversed and no matching member variables are found. Therefore, the efficiency is inherently lower than the form of using member variables. When data structures and data sets are simple and do not require read/write control, you can consider using member variables as attributes to improve efficiency.

Another tips to improve efficiency is: use $ pro = $ object-> getPro () to replace $ pro = $ object-> pro, and use $ objcect-> setPro ($ value) to replace $ object-> pro = $ value. This works exactly the same in terms of functionality, but avoids the use of _ get () and _ set (), which is equivalent to bypassing the traversal process.

Here it is estimated that someone should scold me. Yii has implemented the attribute mechanism to facilitate developers. as a result, I am here to teach you how to use the original method to improve the so-called efficiency. Well, there is indeed a conflict between the convenience of development and the efficiency of execution. My personal opinion is more inclined to take convenience first, and use Yii to create convenient conditions for us. As for efficiency, it is more important for the framework itself to pay attention to. we just need to leave out the extra 2 code.

However, you can rest assured that in the Yii Framework, code such as $ app-> request rarely appears, but $ app-> getRequest () is used (). In other words, the framework itself pays special attention to efficiency. as for convenience, it is left to developers. In short, I just came up with such a knowledge point. it depends on you if you don't need it.

It is worth noting that:

Because the automatic call of _ get () _ set () occurs only when the nonexistent member variable is accessed. Therefore, if the member variable public $ title is defined, it will not be called even if getTitle () setTitle () is defined. Because $ post-> title directly points to the pulic $ title, _ get () _ set () is not called. It is cut off from the root.
Because PHP is case insensitive to class methods, $ post-> getTitle () and $ post-> gettitle () call the same function. Therefore, $ post-> title and $ post-> Title are the same attributes. That is, the attribute name is case insensitive.
Since _ get () _ set () is public, it makes no sense to declare getTitle () setTitle () as public, private, and protected, externally accessible. Therefore, all attributes are public.
Because _ get () _ set () is not static, there is no way to use the static attribute.
Other property-related methods of the Object

In addition to _ get () _ set (), yii \ base \ Object provides the following methods to facilitate attribute usage:

  • _ Isset () is used to test whether the attribute value is not null. it is automatically called when isset ($ object-> property. Note that the property must have a corresponding getter.
  • _ Unset () is used to set the property value to null. it is automatically called When unset ($ object-> property) is used. Note that the property must have a corresponding setter.
  • HasProperty () is used to test whether a property exists. That is, getter or setter is defined. If the hasProperty () parameter $ checkVars = true (the default value is true), the member variable with the same name is considered to have this property, as shown in the public $ title mentioned above.
  • CanGetProperty () tests whether an attribute is readable. the meaning of the $ checkVars parameter is the same as that of the parameter. As long as the getter is defined, the attribute can be read. If $ checkVars is true. As long as the class defines member variables, public, private, and protected, they are considered readable.
  • CanSetProperty () is used to test whether a property can be written. the meaning of the $ checkVars parameter is the same as that of the parameter. As long as the setter is defined, the attribute can be written. At the same time, $ checkVars is true. As long as the class defines member variables, public, private, and protected, they are considered writable.
  • Object and Component

Yii \ base \ Component inherits from yii \ base \ Object. Therefore, it also has basic functions such as attributes.

However, since Componet also introduces events and behaviors, it does not simply inherit the Object attribute implementation method, but is based on the same mechanism, reload _ get () _ set () and other functions. However, the implementation mechanism is the same. This does not affect understanding.

As mentioned above, Yii is officially positioned in a component-based framework. The concept of visible components is the basis of Yii. If you are interested in reading the source code or API documentation of Yii, you will find that almost all Yii core classes are derived from (inherited from) yii \ base \ Component.

At Yii1.1, the component was already in use, and it was CComponent. Yii2 splits CComponent in Yii1.1 into two classes: yii \ base \ Object and yii \ base \ Component.

Objects are relatively lightweight, and properties of the class are defined through getter and setter ). Component is derived from an Object and supports events and behaviors ). Therefore, the Component class has three important features:

  • Property)
  • Event)
  • Behavior (behavior)

I believe you have learned more or less that these three features are an important starting point for enriching and expanding functions and changing behaviors. Therefore, Component has a very high position in Yii.

While providing more functions and convenience, Component has added the event and behavior features to facilitate development and at the same time sacrifice some efficiency. If you do not need to use the event and behavior features during development, such as classes that represent some data. You can inherit from the Object instead of the Component. A typical application scenario is to use an Object if it represents a set of data input by the user. If you need to process the behavior of the object and the event that can respond to the processing, you should undoubtedly use Component. In terms of efficiency, the Object is closer to the native PHP class. Therefore, when possible, the Object should be used first.

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.