本文實例講述了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 目錄
組件 CutomComponent
接口類 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優秀開發框架總結》、《smarty模板入門基礎教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。
您可能感興趣的文章:- 從零開始學YII2框架(六)高級應用程序模板
- yii2高級應用之自定義組件實現全局使用圖片上傳功能的方法
- YII Framework框架使用YIIC快速創建YII應用之migrate用法實例詳解
- YII Framework框架教程之使用YIIC快速創建YII應用詳解
- Yii2框架redis基本應用示例
- Yii框架常見緩存應用實例小結
- Yii Framework框架中事件和行為的區別及應用實例分析
- 再談Yii Framework框架中的事件event原理與應用
- Yii框架應用組件用法實例分析
- Yii 框架應用(Applications)操作實例詳解