Yii2 - 在运行时附加组件 [英] Yii2 - Attach a component on runtime

查看:24
本文介绍了Yii2 - 在运行时附加组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实从数据库中动态询问了组件中设置值的问题,为 swiftmailer 提供了示例.此处>

但该答案仅适用于邮件程序组件,因此我如何实现类似的功能,例如,我需要在我的 config.php 中添加如下值:

'pp' =>['类' =>'app/components/paypal',//注意:这必须与新创建的文件夹相对应,否则你会得到一个 ReflectionError//接下来,我们设置类的公共参数'client_id' =>'您的客户 ID-来自 PAYPAL','client_secret' =>'您的客户 - 来自 PAYPAL 的秘密',//您可以选择包括来自 PayPal 的其他配置选项//正如他们在文档中指定的那样],

解决方案

如果您需要在运行时从数据库提供这些凭据,您可以使用 setComponents() yii\ 的方法base\Application 类,您从数据库中检索贝宝的设置并将其从配置文件中删除.

添加以下几行以在运行时设置组件,然后调用所需的方法

Yii::$app->setComponents(['pp' =>['类' =>'app/components/paypal',//注意:这必须与新创建的文件夹相对应,否则你会得到一个 ReflectionError//接下来,我们设置类的公共参数'client_id' =>'您的客户 ID-来自 PAYPAL','client_secret' =>'您的客户 - 来自 PAYPAL 的秘密'//您可以选择包括来自 PayPal 的其他配置选项//正如他们在文档中指定的那样]]);//现在您可以使用上述凭据为pp调用所需的方法Yii::$app->pp->checkout();

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
  ],

解决方案

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

这篇关于Yii2 - 在运行时附加组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆