A brief analysis of the basic knowledge _php skills of the component-based mechanism of PHP's YII framework

Source: Internet
Author: User
Tags comments yii

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

    • Properties (property)
    • Events (Event)
    • Behavior (Behavior)

or used alone, or with each other, the application of these features makes Yii's classes more flexible and easy to use. As an example of widget Yii\jui\datepicker, this is a UI component that makes it easy for 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 inherits from Yii\base\component, and its properties are easy to rewrite.

Because of the powerful components, they are slightly heavier than regular objects (object) because they 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 features.

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

If you need to rewrite the constructor method (constructor), pass in the $config as the last argument to the constructor method, and pass it to the constructor method of the parent class.
Always call the constructor method of the parent class at the end of the constructor you have rewritten.
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 configuration is in effect
  }


In addition, to allow components to be configured correctly when creating instances, 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 to invoke the Yii::createobject () is more complex, this is largely because it is more flexible and is implemented based on a dependency injection container.
The lifecycle of the Yii\base\object class executes as follows:

The pre-initialization process within the constructor method. You can set the default values for each property here.
Configure the object by $config. The configured procedure may overwrite the default values previously set in the construction method.
The finishing work after initialization within the Yii\base\object::init () method. You can rewrite this method to perform some work such as good inspection, initialization of properties, and so on.
Object method Invocation.
The first three steps occur within the object's construction method. This means that once you have an object instance, it is already initialized and ready to use.

Application Cwebapplication Components
before you explain how each component in Yii uses a 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 that has 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, either set to its public member variable or automatically invoke the Setter method settings property, which can be found in the Cwebapplication constructor: $this- >configure ($config);
As specified in the configuration file protected/config/main.php global:

' CharSet ' => ' Utf-8 ',

This is actually setting the charset public properties of the current application (declared in capplication) and if you specify ' language ' => ' ZH_CN ' in the configuration file, we find that cwebapplication and all its ancestor classes are not declared $ Language property, the setter mode method is used, that is, Setlanuage (this method is defined in the CApplication Class).
OK, once we understand this feature, we can understand the properties that can be configured in the configuration file:

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

The inheritance level of cwebapplication is: capplication-> cmodule-> ccomponent, we describe the configuration items that are common in the default configuration file and their entry into force location:

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

Similarly, list a few configuration items that are not listed in the default profile: 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 individual parts that make up the machine, without the correct combination of the parts, the machine will not function properly, which is the same concept in Yii. Some components are essential to the operation of the whole machine, which is the core component. After the Application object is constructed, Yii enlists the basic information of the auxiliary components (the component name and the class name, the table of the property configuration) for subsequent use, and for the Web application, there are the following core components (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 routing Manager
The items labeled red above are the most important auxiliary components and other core components that we may not use.
How do I define the properties of a secondary component? Implement the Component property definition by setting the value of the components item in the configuration file protected/config/main.php. The definition here is primarily three elements: specifying the name of the component (the core component has been set up beforehand), the class that the specified component uses (the core component is not defined), and the component's properties (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 by the DB component is set to Mycdbconnection, and the connection string and account number are specified later. Hint: The Mycdbconnection class may be defined by inheriting the Cdbconnection class. The core component does not need to specify a class parameter (because it has been predefined).
Question: How do I know the properties that a component can configure? This is a matter of great importance, and if we master the rules, we can extrapolate the configuration of all components can be flexibly set. It is better to teach fish than to teach it. The general approach is described in this section. To learn all the customizable properties for a component, follow these steps:
1. What are the classes used by the component? (whether it's a core component or a custom component)
2. What are the public member variables for the 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)
With the above three points, we can define the attributes of the component by law, such as for the most important DB component, we find that this is a core component, the class used is cdbconnection, and we look at the definition file for this class and find that the public member variables for this class are:

$connectionString;

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

Properties 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 not case-sensitive, and can be specified in the configuration file for each property, see the detailed comments for the Yii class file (the annotations to the Yii code are also pretty good, easy to read, and very detailed).

Another example, defining the properties of the Urlmanager component, the class used by this component is Curlmanager, and we look at its properties:

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

Attributes defined by the Setter method:

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

That is, the above properties of the Urlmanager component can be defined in the configuration file (see its comments for the role of each configuration). The configuration of other components can be handled as described above.

When a component application is run, all of the components that have already been defined are registered (not instantiated) onto the Cwebapplication object, while the Cwebapplication Application object is registered to the Yii::$_app, which can be used in any location of the program via YII:  : App () gets the current Application object reference and then gets 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 common requirement, such as we might want the DB component (database connection) to use our custom class, or we would like to use multiple database connections, in which case we need to customize the component, using the example of multiple databases:

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 am deeply understand the Yii component mechanism to the application of the great extensibility, haha ~

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.