简体   繁体   中英

Overriding Yii components in the controller

I have a Yii 1.x component loaded in the configuration file like so

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

I need to make the autoloadPath property dynamic based on who the user is in the controller. Is this possible? And if so how do I overwrite it?

Probably the best way is to extend Simplesamlphp and configure property in 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();
    }
}

And use new component in config:

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

I figured it out overriding yii components is fairly easy even if you dont initialize it in the config.

$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);

then use the component in your controller like so

    Yii::app()->simplesamlphp;

Note that you will only have access to the component within your controller method so all i did was move the that code to its own class and call it when i needed to create a new instance of the component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM