Yii2 - Attach a component on runtime

2019-08-28 01:53发布

问题:

I did asked a question setting value in component dynamically from database, providing example for swiftmailer. The same was answered perfectly here

but that answer applies to mailer component only, so how I can achieve the similar functionality for example, I need to added in my config.php values like:

'pp' => [ 
    'class' => 'app/components/paypal', // note: this has to correspond with the newly created folder, else you'd get a ReflectionError

     // Next up, we set the public parameters of the class
    'client_id' => 'YOUR-CLIENT-ID-FROM-PAYPAL',
    'client_secret' => 'YOUR-CLIENT-SECRET-FROM-PAYPAL',
    // You may choose to include other configuration options from PayPal
    // as they have specified in the documentation
  ],

回答1:

If you need to provide these credentials from the database on runtime you can define it via your code using the setComponents() method of the yii\base\Application class where you are retrieving the settings from the database for paypal and remove it from the config file.

Add the following lines to set the component on runtime and then call the desired method

Yii::$app->setComponents(
    [
        'pp' => [
            'class' => 'app/components/paypal', // note: this has to correspond with the newly created folder, else you'd get a ReflectionError

            // Next up, we set the public parameters of the class
            'client_id' => 'YOUR-CLIENT-ID-FROM-PAYPAL',
            'client_secret' => 'YOUR-CLIENT-SECRET-FROM-PAYPAL'
            // You may choose to include other configuration options from PayPal
            // as they have specified in the documentation
        ]
    ]
);

//now you can call the desired method for the pp with the above credentials
Yii::$app->pp->checkout();


标签: php yii2