


Components are the main building blocks of Yii applications. Is an instance of the yiibaseComponent class or its subclasses. The three main functions used to distinguish it from other classes are:
- Property
- Event
- Behavior
Used alone or in conjunction with each other, the application of these functions makes Yii classes more flexible and easier to use. Take the widget yiijuiDatePicker as an example. This is a UI component that allows you to generate an interactive date picker in a view:
use yii\jui\DatePicker; echo DatePicker::widget([ 'language' => 'zh-CN', 'name' => 'country', 'clientOptions' => [ 'dateFormat' => 'yy-mm-dd', ], ]);
This widget inherits from yiibaseComponent, and its properties can be easily rewritten.
Precisely because of the powerful functions of components, they are slightly heavier than regular objects (Object) because they use additional memory and CPU time to process events and behaviors. If you don't need these two features, you can inherit yiibaseObject instead of yiibaseComponent. In this way, the component can be as efficient as a normal PHP object, while also supporting the property function.
When inheriting yiibaseComponent or yiibaseObject, it is recommended that you use the following coding style:
If you need to override the constructor (Constructor), pass $config as the last parameter of the constructor method, and then pass it to the constructor of the parent class.
Always call the parent class's constructor at the end of your overridden constructor.
If you override the yiibaseObject::init() method, make sure 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 = []) { // ... 配置生效前的初始化过程 parent::__construct($config); } public function init() { parent::init(); // ... 配置生效后的初始化过程 } }
In addition, in order for the component to be configured correctly when creating an instance, please follow the following operation process:
$component = new MyClass(1, 2, ['prop1' => 3, 'prop2' => 4]); // 方法二: $component = \Yii::createObject([ 'class' => MyClass::className(), 'prop1' => 3, 'prop2' => 4, ], [1, 2]);
Supplement: Although the method of calling Yii::createObject() looks more complicated, this is mainly because it is more flexible and powerful, and it is implemented based on the dependency injection container.
The life cycle of the yiibaseObject class when executed is as follows:
Pre-initialization process within the constructor. You can set default values for each property here.
Configuration objects via $config. The configuration process may overwrite the default values previously set in the constructor.
Perform the finishing work after initialization in the yiibaseObject::init() method. You can override this method to perform some work such as quality inspection and attribute initialization.
Object method call.
The first three steps all occur within the object's constructor. This means that once you obtain an object instance, it is initialized and ready for use.
Application CWebApplication component
Before explaining how to use each component in Yii, let’s first understand the most important component, CWebApplication. CWebApplication is the application object, and its root class is also CComponent, so it is also a component and has the common characteristics of Yii components.
Specifically, the main function of the CWebApplication component is to load necessary auxiliary components according to the configuration file, and create and run the controller with the help of these components (such as urlManager). Therefore, it is also called a front-end controller.
We can specify the configuration parameters of the CWebApplication component itself in the configuration file. These parameters are set to its public member variables, or the setter method is automatically called to set properties. This feature can be found in the constructor of CWebApplication: $this->configure ($config);
As specified in the configuration file protected/config/main.php globally:
'charset' => 'utf-8',
这实际是设置当前应用程序的charset公共属性(在CApplication中声明)而如果在配置文件中指定'language' => 'zh_cn', 我们发现CWebApplication及其所有上级类均未声明$language属性,这时将使用setter模式方法即setlanuage(此方法定义在CApplication类中)。
OK,了解这个特性之后,我们就可以明白在配置文件中可以配置的属性:
- CWebApplication及其所有上级类的公共成员变量
- CWebApplication及其所有上级类的setter方法指定的属性当然我们也可以通过继承CWebApplication构造自己的应用程序类。
CWebApplication的继承层次为:CApplication -> CModule -> CComponent, 我们将默认的配置文件中常见的配置项及其生效位置予以说明:
- basePath : CApplication::setBasePath()
- name: CApplication::$name
- preload: CModule::$preload
- import: CModule::setImport()
- defaultController: CWebApplication::$defaultController
- components: CModule::setComponents()
类似地,再列出几个默认配置文件中并未列出的配置项:timezone: CApplication::setTimeZone() #配置时区
再例如,如果我们继承CWebApplication, 扩展自己的应用程序类myApp, 并定义方法setError_reporting(不区分大小写), 那么就可以直接在配置文件中指定error_reporting选项。
辅助组件可以将CWebApplication组件视为一部机器,那么辅助组件就可以视为组成这部机器的各个零件,没有零件的正确组合,机器就无法正常工作,这在Yii中也是同样的概念。而一些组件对整部机器的运转是必须的,这就是核心组件。在应用程序对象构造后,Yii会将辅助组件基本信息进行登记(组件名称与类名,属性配置的对照表),以供后续使用,对web应用程序而言,存在以下核心组件(通过CWebApplication::registerCoreComponents,CApplication::registerCoreComponents注册):
CWebApplication::registerCoreComponents中注册的核心组件
CApplication::registerCoreComponents中注册的核心组件
配置文本中注册的核心组件:log CLogRouter 日志路由管理器
以上标记为红色的条目,是最重要的辅助组件,其它的核心组件我们未必会使用到。
如何定义辅助组件的属性?通过在配置文件protected/config/main.php中设置components项的值,实现组件属性定义。这里的定义主要是三个要素:指定组件的名称(核心组件已经预先设置)、指定组件使用的类(核心组件无须定义),组件的属性(可选、视情况而定)
如以下配置:
'components' => array( 'db' => array( 'class' => 'myCDbConnection', 'connnectionString' => 'mysql:host=localhost;dbname=test;charset=utf8', 'user' => 'root', ), );
就设置了db组件使用的类为myCDbConnection, 并且在后面指定了连接串及账号等信息。提示: myCDbConnection类可能就是通过继承CDbConnection类定义。核心组件无须指定class参数(因为已经预先定义好)
问题:如何得知某个组件可配置的属性?这个问题至关重要,如果我们掌握了规律,就可以举一反三,所有组件的配置均可以灵活设定。授之以鱼不如授之以渔。在本节会说明通用的方法。要得知组件的所有可定义属性,按以下步骤进行:
1. 组件所使用的类是什么?(无论是核心组件还是自定义组件)
2. 组件类的公共成员变量都有哪些?(注意从父类继承而来的公共成员变量)
3. 组件类都有哪些settter方法?(注意从父类继承而来的方法)
明白了以上三个要点,我们就可以按规律定义组件的属性,比如对最重要的db组件,我们发现这是一个核心组件,使用的类为CDbConnection, 我们查阅这个类的定义文件,发现这个类的公共成员变量有:
$connectionString;
- $username='';
- $password='';
- $autoConnect=true;
- $charset;
- $emulatePrepare;
- $tablePrefix;
- $initSQLs;
- ... ...
setter方法定义的属性:
- setActive($value)
- setAttributes($values)
- setAutoCommit($value)
- setColumnCase($value)
- setNullConversion($value)
- setPersistent($value)
提示:setter方法定义的属性名称不区分大小写以上所列的属性,均可以在配置文件中指定,具体每个属性的作用,请参阅Yii类文件的详细注释(Yii代码的注释也是相当棒,通俗易懂,而又很详细)
再来一个例子,定义urlManager组件的属性这个组件使用的类为CUrlManager, 我们查阅它的属性:
- $rules=array();
- $urlSuffix='';
- $showScriptName=true;
- $appendParams=true;
- $routeVar='r';
- $caseSensitive=true;
通过setter方法定义的属性:
- setUrlFormat($value)
- setBaseUrl($value)
即urlManager组件的上述属性可以在配置文件中定义(每项配置的作用请参阅其注释)。其它组件的配置均可按上述方法处理。
如何使用组件应用程序运行后,会将所有已经定义过的组件注册(并未实例化)到CWebApplication对象上,同时CWebApplication应用程序对象会被注册到Yii::$_app,在程序的任何位置均可通过Yii::app()得到当前应用程序对象引用,再通过$app对象得到组件实例引用,如:Yii::app()->getComponent('urlManager'); #会查找组件配置并实例化之Yii::app()->urlManager; #通过CModule::__get()魔术方法实现
如何自定义组件?这是很常见的需求,比如我们可能希望db组件(数据库连接)使用我们自定义的类,也或者我们希望使用多个数据库连接,这种情况下就需要自定义组件,使用多数据库的例子:
components=>array( 'db' => array( ... ... ), 'mydb'=>array( 'class' => 'myDbConnection', 'connectionString' => 'mysql:host=localhost;dbname=test;charset=utf8', 'tablePrefix' => 'cdb_', 'username' => 'root', ), ), 修改默认的db组件所使用的类: components=>array( 'db' => array( 'class' => 'myDbConnection', ... ... ), ),
经过本文的分析,我是深切理解了Yii组件化机制给应用程序带来的极大的扩展性,哈哈哈哈~

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!
