Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of the component Mechanism in the Yii Framework of PHP

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "sample analysis of the component-based mechanism in PHP's Yii framework", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of the component-based mechanism in PHP's Yii framework".

Component is the main cornerstone of Yii application. Is an instance of the yii\ base\ Component class or its subclasses. The three main functions that distinguish it from other categories are:

Attribute (Property)

Event (Event)

Behavior (Behavior)

Whether used alone or in conjunction with each other, the application of these functions makes Yii classes more flexible and easy to use. Take the widget yii\ jui\ DatePicker, for example, 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 can be easily overwritten.

Because of the power of components, they are slightly more heavyweight 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 functionality.

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

If you need to override the constructor method (Constructor), pass in $config as the last parameter of the constructor method, and pass it to the constructor of the parent class.

Always call the constructor of the parent class at the end of your overridden constructor.

If you override the yii\ base\ Object::init () method, make sure that you call the parent class's init method at the beginning of the init method.

Examples are as follows:

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

In addition, in order for the component to be configured correctly when creating the instance, follow the following procedure:

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

Add: although the method of calling Yii::createObject () looks more complex, this is mainly because it is more flexible and powerful, and it is implemented based on the dependency injection container.

The life cycle when the yii\ base\ Object class executes is as follows:

The preinitialization process within the constructor. You can set default values for each property here.

Configure the object through $config. The process of configuration may override the default values previously set in the constructor.

Finalize the initialization in the yii\ base\ Object::init () method. You can rewrite this method to do some good inspection, property initialization and so on.

Object method call.

The first three steps take place within the constructor of the object. This means that once you have an object instance, it is initialized and ready to use.

Application CWebApplication component

Before explaining how to use the various components in Yii, learn about the most important component, CWebApplication. CWebApplication is an application object, and its root class is also CComponent, so it is also a component with the common characteristics of Yii components.

Specifically, the main 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). Therefore, it is also called front-end controller.

We can specify the configuration parameters of the CWebApplication component itself in the configuration file, which are set to its public member variables, or automatically call the setter method to set the property, which can be found in the constructor of 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 we specify 'language' = >' zh_cn', in the configuration file, we find that CWebApplication and all its parent classes do not declare the $language property, then we will use the setter mode method, 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 of CWebApplication and all its parent classes

The properties specified by the setter methods of CWebApplication and all its parent classes, of course, we can also construct our own application classes by inheriting from CWebApplication.

The inheritance hierarchy 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::$defaultController

Components: CModule::setComponents ()

Similarly, list a few more configuration items that are not listed in the default configuration file: timezone: CApplication::setTimeZone () # configuration time zone

For example, if we inherit CWebApplication, extend our application class myApp, and define a method setError_reporting (case-insensitive), we can specify the error_reporting option directly in the configuration file.

Auxiliary components can regard CWebApplication components as a machine, then auxiliary components can be regarded as the various 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, this is the core component. After the application object is constructed, Yii registers the basic information of the auxiliary component (component name and class name, comparison table of property configuration) for subsequent use, and for web applications, the following core components exist (registered through CWebApplication::registerCoreComponents,CApplication::registerCoreComponents):

Core components registered in CWebApplication::registerCoreComponents

Core components registered in CApplication::registerCoreComponents

The core component registered in the configuration text: log CLogRouter log routing manager

The above items marked in red are the most important auxiliary components, and we may not use other core components.

How do I define the properties of an auxiliary component? The component property definition is implemented by setting the value of the components item in the configuration file protected/config/main.php. The definition here is mainly composed of three elements: the name of the specified component (the core component is preset), the class to be used by the specified component (the core component does not need to be defined), and the properties of the component (optional, depending on the situation)

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. Tip: the myCDbConnection class may be defined by inheriting the CDbConnection class. Core components do not need to specify class parameters (because they are pre-defined)

Question: how do I know the configurable properties of a component? This issue is very important, if we master the rules, we can draw an example, and the configuration of all components can be set flexibly. It is better to teach fish than to teach them to fish. General methods are described in this section. To learn all the definable properties of a component, follow these steps:

1. What classes are used by the component? (whether core components or custom components)

two。 What are the common member variables of a component class? (note the public member variables inherited from the parent class)

3. What settter methods do component classes have? (note the methods inherited from the parent class)

After understanding the above three main points, we can define the properties of the component according to the law. For example, for the most important db component, we find that this is a core component, and the class used is CDbConnection. We look up the definition file of this class and find that the public member variables of this class are:

$connectionString

$username=''

$password=''

$autoConnect=true

$charset

$emulatePrepare

$tablePrefix

$initSQLs

......

The 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 the role of each property, please refer to the detailed comments in the Yii class file (the comments on Yii code are also great, easy to understand, and very detailed)

For another example, define the properties of the urlManager component. The class used by this component is CUrlManager. Let's 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)

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

How to use a component application to run, all defined components will be registered (not instantiated) to the CWebApplication object, and the CWebApplication application object will be registered to the Yii::$_app, and the current application object reference can be obtained through Yii::app () anywhere in the program, and then the component instance reference can be obtained through the $app object, such as: Yii::app ()-> getComponent ('urlManager') # Yii::app () that looks up the component configuration and instantiates it-> urlManager; # is implemented through the CModule::__get () magic method

How do I customize components? This is a very common requirement, for example, we may want the db component (database connection) to use our custom class, or we may want to use multiple database connections, in which case we need custom components, using multiple database examples:

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',......),). The above is all the content of this article entitled "sample Analysis of componentization Mechanism in PHP's Yii Framework". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report