A brief analysis of the basic knowledge of the modular mechanism of the YII framework of PHP, YII framework _php Tutorial

Source: Internet
Author: User
Tags yii

A brief analysis of the basic knowledge of the modular mechanism of the YII framework of PHP, YII framework


Components are the main cornerstone of YII applications. is an instance of the Yii\base\component class or its subclasses. The three main functions used to differentiate it from other classes are:

    • Attribute (property)
    • Events (Event)
    • Behavior (Behavior)

or used alone, or in conjunction with each other, the application of these features makes YII classes more flexible and easy to use. As an example of widget Yii\jui\datepicker, this is a UI component that allows you to generate an interactive date selector in a view:

Use Yii\jui\datepicker;echo datepicker::widget ([  ' language ' = ' zh-cn ',  ' name ' = ' country ',  ' Clientoptions ' = [    ' dateformat ' = ' yy-mm-dd ',  ],];

This widget inherits from Yii\base\component, and its various properties can be easily rewritten.

Because of the power of the components, they are slightly heavier than regular objects (object) because they want to use extra memory and CPU time to handle events and behaviors. If you don't need these two features, you can inherit yii\base\object instead of yii\base\component. This allows components to be as efficient as normal PHP objects, while also supporting property functionality.

When inheriting yii\base\component or yii\base\object, it is recommended that you use the following encoding style:

If you need to override the constructor method (Constructor), pass in the $config as the last parameter of the constructor method, and transfer it to the constructor of the parent class.
Always call the constructor of the parent class at the end of your overridden constructor method.
If you rewrite 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.
Examples are as follows:

Namespace Yii\components\myclass;use yii\base\object;class MyClass extends object{public  $prop 1;  Public $prop 2;  Public Function __construct ($param 1, $param 2, $config = [])  {    //...) The initialization process before the configuration takes effect    parent::__construct ($config);  }  Public function init ()  {    parent::init ();    // ... Initialization process After the configuration is in effect  }}

In addition, in order for components to be properly configured when creating an instance, follow these procedures:

$component = new MyClass (1, 2, [' Prop1 ' = 3, ' prop2 ' = 4]);//Method Two: $component = \yii::createobject ([  ' class ' = > Myclass::classname (),  ' prop1 ' = 3,  ' prop2 ' = 4,], [1, 2]);

Add: Although the method of calling Yii::createobject () looks more complex, it is mainly because it is more flexible and powerful, and it is implemented based on the dependency injection container.
The Yii\base\object class executes at the following life cycle:

The pre-initialization process within the constructor method. You can set the default values for each property here.
The object is configured by $config. The configured procedure may overwrite the default values that were previously set in the constructor method.
The end-of-process after initialization within the Yii\base\object::init () method. You can do some good testing, the initialization of properties, and so on, by overriding this method.
The object method call.
The first three steps occur within the object's construction method. This means that once you have an object instance, it is already initialized ready to be used.

Application Cwebapplication Components
Before explaining how each component in Yii uses the method, first understand the most important component cwebapplication. Cwebapplication is the Application object, its root class is also ccomponent, so it is also a component, with the common characteristics of YII components.
Specifically, the primary role of the cwebapplication component is to load the necessary auxiliary components based on the configuration file, and to create and run the controller with the help of these components, such as Urlmanager. It is also called a front-end controller.
We can specify the configuration parameters of the Cwebapplication component itself in the configuration file, which is set to its public member variable, or the Setter method setting property is called automatically, which can be found in the constructor of the cwebapplication: $this- >configure ($config);
As specified in the configuration file protected/config/main.php global:

' CharSet ' = ' utf-8 ',

This is actually setting the CharSet public property of the current application (declared in capplication) and if you specify ' language ' = ' zh_cn ' in the configuration file, we find that cwebapplication and all of its ancestor classes do not declare $ Language property, the setter mode method is used, which is setlanuage (this method is defined in the CApplication Class).
OK, after understanding this feature, we can understand the properties that can be configured in the configuration file:

    • Public member variables for Cwebapplication and all of its ancestor classes
    • Cwebapplication and all of its ancestor classes The setter method specifies the properties of course we can also construct our own application classes by inheriting cwebapplication.

The inheritance hierarchy for cwebapplication is: ccomponent, Cmodule-CApplication, we will describe the configuration items that are common in the default configuration file and their effective locations:

    • Basepath:capplication::setbasepath ()
    • Name:capplication:: $name
    • Preload:cmodule:: $preload
    • Import:cmodule::setimport ()
    • Defaultcontroller:cwebapplication:: $defaultController
    • Components:cmodule::setcomponents ()

Similarly, several configuration items that are not listed in the default configuration file are listed: Timezone:capplication::settimezone () #配置时区

For example, if we inherit cwebapplication, extend our own application class MyApp, and define method seterror_reporting (case insensitive), then you can specify the error_reporting option directly in the configuration file.
The auxiliary component can treat the Cwebapplication component as a machine, then the auxiliary component can be regarded as the parts that make up the machine, without the correct combination of parts, the machine will not work properly, which is the same concept in Yii. And some components are necessary for the operation of the whole machine, and this is the core component. After the Application object is constructed, Yii enlists the basic information of the auxiliary component (the component name and the class name, the table of the property configuration) for subsequent use, and for the Web application, the following core components exist (via cwebapplication:: Registercorecomponents,capplication::registercorecomponents registration):

Core components registered in the Cwebapplication::registercorecomponents

Core components registered in the Capplication::registercorecomponents

Core components registered in the configuration text: Log clogrouter logging route Manager
The above items marked in red are the most important auxiliary components, and other core components we may not use.
How do I define the properties of an auxiliary component? Implement the Component property definition by setting the values of the components in the configuration file protected/config/main.php. The definition here is primarily three elements: specifying the name of the component (the core component is pre-set), the class used by the specified component (the core component does not need to be defined), the properties of the component (optional, as appropriate)
such as the following configuration:

' Components ' + = Array (' db ' = = Array (' class ' = ' mycdbconnection ', ' connnectionstring ' = ' mysql:host= ') Localhost;dbname=test;charset=utf8 ', ' user ' = ' root ',);

The class used for the DB component is set to Mycdbconnection, and the connection string and account 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)
Question: How do I know which properties a component can configure? This is a matter of vital importance, and if we have mastered the rules, we can extrapolate the configuration of all components can be flexibly set. It is better to give the fish than to give it. The common approach is described in this section. To learn all the definable properties of a component, follow these steps:
1. What are the classes used by the components? (whether it's a core component or a custom component)
2. What are the common member variables for a component class? (Note Public member variables inherited from the parent class)
3. What are the Settter methods for component classes? (Note the method inherited from the parent class)
Understanding the above three points, we can define the properties of the component according to the law, for example, for the most important DB component, we find this is a core component, using the class as cdbconnection, we look up the definition file of this class, we find that the common member variables of this class are:

$connectionString;

    • $username = ";
    • $password = ";
    • $autoConnect =true;
    • $charset;
    • $emulatePrepare;
    • $tablePrefix;
    • $initSQLs;
    • ... ...

Properties defined by setter methods:

    • SetActive ($value)
    • SetAttributes ($values)
    • Setautocommit ($value)
    • Setcolumncase ($value)
    • Setnullconversion ($value)
    • Setpersistent ($value)

Hint: the property names defined by the setter method are not case-sensitive, and can be specified in the configuration file, for each property, see detailed comments on the Yii class file (the comments of the Yii code are also quite good, easy to understand, and very detailed)

One more example, defining the properties of the Urlmanager component this component uses a class of Curlmanager, and we look at its properties:

    • $rules =array ();
    • $urlSuffix = ";
    • $showScriptName =true;
    • $appendParams =true;
    • $routeVar = ' R ';
    • $caseSensitive =true;

Properties defined by the Setter method:

    • Seturlformat ($value)
    • Setbaseurl ($value)

The above attributes of the Urlmanager component can be defined in the configuration file (see its comments for the purpose of each configuration). The configuration of other components can be handled as described above.

When running with a component application, all defined components are registered (not instantiated) on the Cwebapplication object, and the Cwebapplication Application object is registered to Yii::$_app, which can be used at any location in the program via YII: : the app () obtains the current Application object reference, and then obtains the component instance reference through the $app object, such as: Yii::app ()->getcomponent (' Urlmanager '); #会查找组件配置并实例化之Yii:: App ()->urlmanager; #通过CModule:: __get () Magic Method implementation
How do I customize a component? This is a very common requirement, such as we might want DB components (database connections) to use our custom classes, or we want to use multiple database connections, in which case we need to customize the components and use the multi-database example:

Components=>array (' db ' = = Array (...), ' MyDB ' =>array (' class ' = ' mydbconnection ', ' connectionString ' = > ' 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 the analysis of this article, I deeply understand the Yii component mechanism to the application brought about by the great extensibility, haha ~

Articles you may be interested in:

    • The definition and binding methods of behavior in the YII framework of PHP
    • A detailed approach to using behavioral behaviors in the PHP yii framework
    • In-depth explanation of properties in the Yii framework of PHP
    • Interpreting the process of request and response in the YII framework of PHP
    • PHP's YII framework uses database configuration and SQL Operations example tutorials
    • Examples of how to do error and exception handling in the PHP yii framework
    • Parsing of PHP in the YII framework of the cookie and session function related operations
    • Examples of extensions to the Yiibase portal class in the PHP yii framework
    • The operation mechanism and routing function of the YII framework of PHP
    • In-depth parsing of event events mechanism in the YII framework of PHP
    • Full interpretation of the log function in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework

http://www.bkjia.com/PHPjc/1111321.html www.bkjia.com true http://www.bkjia.com/PHPjc/1111321.html techarticle The basic knowledge of the modular mechanism of the YII framework of PHP is briefly analyzed, and the YII framework component is the main cornerstone of YII application. is an instance of the Yii\base\component class or its subclasses. Three to differentiate it ...

  • Related Article

    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.