簡體   English   中英

覆蓋控制器中的Yii組件

[英]Overriding Yii components in the controller

我在配置文件中加載了一個Yii 1.x組件,如下所示

$config['components']['simplesamlphp'] = array(
      'class' => 'application.components.yii-simplesamlphp.components.Simplesamlphp',
      'autoloadPath' => SAML_DIR.'/test2/lib/_autoload.php',
      'authSource' => 'default-sp',
);

我需要根據用戶在控制器中的身份來使autoloadPath屬性動態化。 這可能嗎? 如果是這樣,我該如何覆蓋它?

最好的方法可能是擴展Simplesamlphp並在init()配置屬性:

class MySimplesamlphp extends Simplesamlphp {

    public $adminAutoloadPath;
    public $nonAdminAutoloadPath;

    public function init() {
        if (Yii::app()->user->isAdmin()) {
            $this->autoloadPath = $this->adminAutoloadPath;
        } else {
            $this->autoloadPath = $this->nonAdminAutoloadPath;
        }

        parent::init();
    }
}

並在配置中使用新組件:

$config['components']['simplesamlphp'] = array(
    'class' => 'MySimplesamlphp',
    'adminAutoloadPath' => SAML_DIR.'/test2-admin/lib/_autoload.php',
    'nonAdminAutoloadPath' => SAML_DIR.'/test2/lib/_autoload.php',
    'authSource' => 'default-sp',
);

我發現覆蓋yii組件非常簡單,即使您沒有在配置中對其進行初始化。

$component  =   array(
                  'class' => 'application.components.yii-simplesamlphp.components.Simplesamlphp',
                  'autoloadPath' => SAML_DIR.'/'.$tenant_path.'/lib/_autoload.php',
                  'authSource' => 'default-sp',
                    ); //where $tenant_path is the directory of the component i need based on the tenant

    Yii::app()->setComponent('simplesamlphp',$component);

然后像這樣使用控制器中的組件

    Yii::app()->simplesamlphp;

請注意 ,您將只能訪問控制器方法中的組件,因此我所做的只是將代碼移至其自己的類中,並在需要創建組件的新實例時調用它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM