Yii应用组件配置基础
本示例深入解析Yii框架中应用组件的操作机制,旨在为开发者提供实用的参考指南。
所有自定义组件的定义必须放置在配置文件 config/web.php 中。
//组件声明在该数组下
'components'=>array(
//自定义组件1 - 函数形式
'customComponent1' => function(){
$custom = new app\components\CustomComponent\realization\CustomComponent1();
$custom->setName('谭勇');
$custom->setAge(22);
return $custom;
},
//自定义组件2 - 数组形式
'customComponent2' => array(
'class' => 'app\components\CustomComponent\relazation\CustomComponent2'
'name' => '谭勇',
'age' => 22
),
//自定义组件 - 字符串形式
'customComponent3' => 'app\components\CustomComponent\realization\CustomComponent3'
),
组件的实例化行为取决于其声明位置。若仅在 components 数组中声明,该组件将在首次被访问时才进行实例化,后续调用将复用同一实例;若将其加入 bootstrap 数组,则该组件会伴随应用主体的初始化过程自动实例化,无需等待首次调用。
//默认加载customComponent1 和 customComponent2 组件
'bootstrap' => array(
'customComponent1','customComponent2'
),
首先需在应用根目录下建立 components 目录以存放相关类文件。
接下来定义一个名为 CustomComponent 的自定义组件。
对应的接口类路径定义为 app\components\CustomComponent\CustomComponent。
<?php
namespace app\components\CustomComponent;
interface CustomComponent
{
public function setName($name);
public function setAge($age);
public function getName();
public function getAge();
}
?>
具体的实现类位于 app\components\CustomComponent\realization\CustomComponent1。
<?php
namespace app\components\CustomComponent\realization;
use app\components\CustomComponent\CustomComponent;
class CustomComponent1 implments CustomComponent
{
public $name='勇哥';
public $age = '我的年龄';
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setAge($age)
{
$this->age = $age;
}
public function getAge()
{
return $this->age;
}
}
?>
为了简化演示,customComponent2 和 customComponent3 的代码逻辑与 customComponent1 保持一致。本文将重点探讨如何正确调用这些已配置的组件。
namespace app\controllers\home;
use Yii;
use yii\web\Controller;
class IndexController extends Controller
{
public function actionIndex()
{
//组件customComponent1
echo Yii::$app->customComponent1->getName();
//组件customComponent2
echo Yii::$app->customComponent2->getName();
//组件customComponent3
echo Yii::$app->customComponent3->getName();
}
}
随后分析组件在配置文件中采用的三种不同形式:数组形式、函数形式以及字符串形式。
//函数形式 - 这个很容易理解 实例化后设置属性值
function(){
$custom = new app\components\CustomComponent\realization\CustomComponent1();
$custom->setName('谭勇');
$custom->setAge(22);
return $custom;
},
//数组形式 - 它会实例化这个组件 之后设置属性值 注意这里设置属性值的方法 和 函数不一样,它是 $custom->name = '谭勇' , $custom->age = 22
array(
'class' => 'app\components\CustomComponent\relazation\CustomComponent2'
'name' => '谭勇',
'age' => 22
),
//字符串形式 只知道会实例化这个组件,怎么注入属性值,这个不清楚支不支持
明确组件的核心作用对于理解其设计模式至关重要。
熟悉 Java Spring MVC 的开发者容易理解这一概念,Yii 中的组件可充当服务层或数据访问层等角色,实现业务逻辑的解耦。
期望上述内容能帮助读者更好地掌握基于 Yii 框架的 PHP 程序设计技巧。