Briefly analyzes the basic knowledge of the componentization mechanism of the Yii framework of PHP, And the yii framework

Source: Internet
Author: User

Briefly analyzes the basic knowledge of the componentization mechanism of the Yii framework of PHP, And the yii framework

Components are the main cornerstone of Yii applications. Is an instance of the yii \ base \ Component class or its subclass. Three main functions used to distinguish it from other classes are:

  • Property)
  • Event)
  • Behavior (Behavior)

These functions can be used independently or in combination with each other to make the Yii class more flexible and easy to use. The following is an example of a widget yii \ jui \ DatePicker. This is a UI component that allows you to generate an interactive date selector in the View:

use yii\jui\DatePicker;echo DatePicker::widget([  'language' => 'zh-CN',  'name' => 'country',  'clientOptions' => [    'dateFormat' => 'yy-mm-dd',  ],]);

This widget is inherited from yii \ base \ Component, and its attributes are easily rewritten.

It is precisely because of the powerful component functions that they are a little more important than conventional objects because they need to use extra memory and CPU time to process events and behaviors. If you do not need these two functions, You can inherit yii \ base \ Object instead of yii \ base \ Component. In this way, components can be as efficient as common PHP objects, and the Property function is also supported.

When inheriting yii \ base \ Component or yii \ base \ Object, we recommend that you use the following encoding style:

If you need to override Constructor, Input $ config as the last parameter of the Constructor method, and then pass it to the Constructor of the parent class.
Always call the constructor of the parent class at the end of the constructor you override.
If you overwrite the yii \ base \ Object: init () method, make sure that you call the init method of the parent class at the beginning of the init method.
Example:

Namespace yii \ components \ MyClass; use yii \ base \ Object; class MyClass extends Object {public $ prop1; public $ prop2; public function _ construct ($ param1, $ param2, $ config = []) {//... initialization process before the configuration takes effect: parent :__ construct ($ config);} public function init () {parent: init ();//... initialization process after the configuration takes effect }}

In addition, to allow the components to be correctly configured when an instance is created, follow these steps:

$ Component = new MyClass (1, 2, ['prop1' => 3, 'prop2' => 4]); // Method 2: $ component = \ Yii :: createObject (['class' => MyClass: className (), 'prop1' => 3, 'prop2' => 4,], [1, 2]);

Supplement: Although calling the Yii: createObject () method looks more complex, it is mainly because it is more flexible and powerful and implemented based on the dependency injection container.
The lifecycle of the yii \ base \ Object class is as follows:

The pre-initialization process in the constructor. You can set the default values for each attribute here.
Configure the object through $ config. The configuration process may overwrite the default values set in the constructor.
Complete the initialization in the yii \ base \ Object: init () method. You can rewrite this method to perform some good product inspection, attribute initialization, and other work.
Object method call.
The first three steps occur in the object constructor. This means that once you get an object instance, it is ready for use.

Application CWebApplication component
Before you describe how to use each component in Yii, you must first understand the most important component CWebApplication. CWebApplication is an application object, and its root class is also CComponent. Therefore, it is also a component and has the common characteristics of the Yii component.
Specifically, the CWebApplication component is used to load necessary auxiliary components based on the configuration file, and create and run controllers with the help of these components (such as urlManager. Therefore, it is also called a front-end controller.
You can specify the configuration parameters of the CWebApplication component in the configuration file. These parameters are set to their public member variables or the setter method is automatically called to set properties, this feature can be found in the CWebApplication constructor: $ this-> configure ($ config );
For example, in the configuration file protected/config/main. php, specify:

'charset' => 'utf-8',

This is actually to set the charset public attribute of the current application (declared in CApplication). If you specify 'language' => 'zh _ cn 'in the configuration file ', we found that CWebApplication and all its upper-level classes do not declare the $ language attribute. In this case, the setter mode method is used, that is, setlanuage (this method is defined in the CApplication class ).
OK. After understanding this feature, we can understand the attributes that can be configured in the configuration file:

  • CWebApplication and all common member variables of the parent class
  • The attributes specified by the setter method of CWebApplication and all its upper-level classes can also be inherited to construct their own application classes.

The inheritance level of CWebApplication is CApplication-> CModule-> CComponent. We will describe the common configuration items in the default configuration file and their effective locations:

  • BasePath: CApplication: setBasePath ()
  • Name: CApplication: $ name
  • Preload: CModule ::$ preload
  • Import: CModule: setImport ()
  • DefaultController: CWebApplication: $ defacontroller Controller
  • Components: CModule: setComponents ()

Similarly, the following configuration items are not listed in the default configuration files: timezone: CApplication: setTimeZone () # configure the time zone.

For example, if we inherit CWebApplication, extend our application class myApp, and define the method setError_reporting (case-insensitive), you can directly specify the error_reporting option in the configuration file.
The auxiliary components can regard the CWebApplication component as a machine, so the auxiliary components can be considered as the parts of the machine. Without the correct combination of the parts, the machine will not work normally, this is also the same concept in Yii. Some components are necessary for the operation of the entire machine, which is the core component. After the application object is constructed, Yii registers the basic information of the auxiliary components (component name, class name, and attribute configuration table) for future use. For web applications, the following core components exist (registered through CWebApplication: registerCoreComponents, CApplication: registerCoreComponents ):

CWebApplication: Core Component registered in registerCoreComponents

CApplication: Core Component registered in registerCoreComponents

Configure the core component registered in the text: log CLogRouter log route manager
The entries marked as red above are the most important auxiliary components. We may not use other core components.
How do I define the attributes of a secondary component? You can set the value of the components item in the configuration file protected/config/main. php to define the component attributes. The definition here mainly includes three elements: Specify the component name (the core component has been pre-set) and specify the class used by the component (the core component does not need to be defined ), component attributes (optional, depending on the situation)
The configuration is as follows:

'components' => array('db' => array('class' => 'myCDbConnection','connnectionString' => 'mysql:host=localhost;dbname=test;charset=utf8','user' => 'root',),);

The class used by the db Component is set to myCDbConnection, and the connection string, account, and other information are specified later. Tip: The myCDbConnection class may be defined by inheriting the CDbConnection class. The Core Component does not need to specify the class parameter (because it is pre-defined)
Q: How do I know the configurable attributes of a component? This problem is crucial. If we have mastered the rule, we can draw a line between them, and the configuration of all components can be set flexibly. It is better to authorize fish to fish. This section describes common methods. To learn all the definable attributes of a component, follow these steps:
1. What is the class used by the component? (Whether it is a core component or a custom component)
2. What are common member variables of the component class? (Note the common member variables inherited from the parent class)
3. What settter methods are available for component classes? (Note the methods inherited from the parent class)
After understanding the above three key points, we can define the attributes of the component according to the rules. For example, for the most important db Component, we find that this is a core component and the class used is CDbConnection, we checked the definition file of this class and found that the common member variables of this class are:

$ ConnectionString;

  • $ Username = '';
  • $ Password = '';
  • $ AutoConnect = true;
  • $ Charset;
  • $ EmulatePrepare;
  • $ TablePrefix;
  • $ InitSQLs;
  • ......

Attributes defined by the setter method:

  • SetActive ($ value)
  • SetAttributes ($ values)
  • SetAutoCommit ($ value)
  • SetColumnCase ($ value)
  • SetNullConversion ($ value)
  • SetPersistent ($ value)

Tip: The property names defined by the setter method are case-insensitive and can be specified in the configuration file, please refer to the detailed comments of Yii files (the comments of Yii Code are also very good, easy to understand, and very detailed)

Let's take another example to define the attributes of the urlManager component. The class used by this component is CUrlManager. Let's look at its attributes:

  • $ Rules = array ();
  • $ UrlSuffix = '';
  • $ ShowScriptName = true;
  • $ AppendParams = true;
  • $ RouteVar = 'R ';
  • $ CaseSensitive = true;

Attributes defined using the setter method:

  • SetUrlFormat ($ value)
  • SetBaseUrl ($ value)

That is, the above attributes of the urlManager component can be defined in the configuration file (for the purpose of each configuration, see its annotations ). The configurations of other components can be processed as described above.

After a component application is run, all defined components are registered (not instantiated) to the CWebApplication object, and the CWebApplication object is registered to Yii :: $ _ app, you can get the reference of the current application object from Yii: app () anywhere in the program, and then get the reference of the component instance through the $ app object, such as: Yii :: app ()-> getComponent ('urlmanager'); # Yii: app ()-> urlManager; # Use CModule :__ get () magic implementation
How do I customize components? This is a common requirement. For example, we may want the db Component (database connection) to use our custom class, or we want to use multiple database connections, in this case, you need to customize components. The example of using multiple databases is as follows:

Components => array ('db' => array (......), 'mydb' => array ('class' => 'mydbconnection', 'ononstring' => 'mysql: host = localhost; dbname = test; charset = utf8 ', 'tableprefix' => 'cdb _ ', 'username' => 'root',),), modify the class used by the default db Component: components => array ('db' => array ('class' => 'mydbconnection ',......),),

After analysis in this article, I deeply understand the great scalability brought by the Yii componentization mechanism to applications ~

Articles you may be interested in:
  • Definition and binding of behavior in PHP Yii framework
  • Detailed description of Behaviors in PHP Yii framework
  • In-depth explanation of attributes in PHP Yii framework)
  • Interpreting the request and Response Processing Process in PHP Yii framework
  • Tutorial on using database configuration and SQL operations in PHP Yii framework
  • The example explains how to handle errors and exceptions in the PHP Yii framework.
  • Parse related operations of cookie and session functions in PHP Yii framework
  • Example of YiiBase entry class extension in the Yii framework of PHP
  • Describes the operating mechanism and routing function of the Yii framework of PHP.
  • In-depth analysis of event mechanism in PHP Yii framework
  • A comprehensive explanation of the log function in the PHP Yii framework
  • How to remove the behavior bound to a component from the Yii framework of PHP

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.