Yii2 - Attach a component on runtime

谁说我不能喝 提交于 2019-12-11 17:34:18

问题


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


来源:https://stackoverflow.com/questions/56711056/yii2-attach-a-component-on-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!