1. 程式人生 > >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 目錄
元件 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 那麼就不難理解元件的作用 可以作為服務層,資料訪問層等等