我想完成Yii2对config
文件中的组件所做的事情
在yii config
:
'someComponent'=>
[
'class' => '\namespace\to\class',
'param1' => 'somevalue',
'param2' => 'somevalue',
]
我怎么能做Yii在我自己的类中做的,给它一个组件文件数组然后我的类创建和实例并初始化它?
编辑:
配置文件:
'payment' => [
'class' => 'backend\modules\payment\Bank',
'components' => [
'service' => [
'class' => 'backend\modules\payment\components\Service',
'adaptors'=>[
'BankMeli' => [
'class'=>'backend\modules\payment\adaptors\BankMeli',
'test'=>'1',
]
]
],
],
],
服务组件:
namespace backend\modules\payment\components;
use Yii;
use yii\base\Component;
class Service extends Component
{
public $adaptors = [];
public function init()
{
parent::init();
$adaptors = new \stdClass();
foreach($this->adaptors as $key=>$adaptor)
{
$class = $adaptor['class'];
unset($adaptor['class']);
$adaptors->$key = Yii::createObject($class,$adaptor);
}
$this->adaptors = $adaptors;
}
public function run()
{
}
}
需要初始化的内部组件(BankMeli):
namespace backend\modules\payment\adaptors;
use Yii;
use yii\base\Component;
class BankMeli extends Component
{
public $test;
public function __construct($config = [])
{
parent::__construct($config);
}
public function init(){
parent::init();
}
}
var_dump(service-> adapters)输出:
object(stdClass)[61]
public 'BankMeli' =>
object(backend\modules\payment\adaptors\BankMeli)[72]
public 'test' => null
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) => null
解决:
我在另一个数组中传递了param数组并解决了问题:
$adaptors->$key = Yii::createObject($class,[$adaptor]);
答案 0 :(得分:0)
使用Yii::createObject()
yii2在配置文件中使用config创建组件对象。就像这样:
Yii::createObject($config['class'], $config['otherParamsWithoutClass']);
yii2中的任何内容扩展Object
类,在构造函数中我们可以输入config params。 param1
和param2
应该是公共属性,或者模型应该有getter和setter。
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}