您可以使用自己的“服务层”(与全球的Yii::$app
类似)。只要创建\yii\di\ServiceLocator
例如:
// Init service layer.
$services = new ServiceLocator();
$services->setComponents([
'imap' => [
'class' => 'roopz\imap\Imap',
'connection' => [
'imapPath' => '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX',
'imapLogin' => '[email protected]',//set this value dynamically
'imapPassword' => '123',//set this value dynamically
'serverEncoding' => 'encoding', // utf-8 default.
'attachmentsDir' => 'uploads/attachments'
],
],
// ...
]);
// Retrieving the defined components:
$imap = $services->get('imap');
$imap = $services->imap;
如果imap
组件将只使用您的控制器,可以存储$services
作为该控制器的保护/私有财产。 描述的方法与Yii::$app
中的常用组件完全相同,因为应用程序类也是ServiceLocator。
或者,您也可以定义或使用IMAP实例重新定义你的组件:
// Preparing components
$defaultImapConfig = [
'connection' => [
'imapPath' => '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX',
'imapLogin' => null,
'imapPassword' => null,
'serverEncoding' => 'encoding', // utf-8 default.
'attachmentsDir' => 'uploads/attachments'
],
];
// Init service layer.
$services = new ServiceLocator();
// Define component
$imap = new \roopz\imap\Imap(ArrayHelper::merge($defaultImapConfig, ['connection' => [
'imapLogin' => '[email protected]',
'imapPassword' => '123',
]]));
$services->set('imap', $imap);
// Redefine component with new config
$imap = new \roopz\imap\Imap(ArrayHelper::merge($defaultImapConfig, ['connection' => [
'imapLogin' => '[email protected]',
'imapPassword' => '456',
]]));
$services->set('imap', $imap); // If component definition with the same name already exist, it will be ovewritten.
当然,你也可以用类似的方式在Yii::$app
重新定义全球的组件,但它是不好的做法。我建议创建单独的(本地)服务层,可以从您的控制器,模型等访问。
有关使用服务定位器的更多详细信息,请参阅here。
能否请您简要 –
您需要Yii2的扶养注入容器解释,请点击这里:HTTP://计算器。com/questions/32689230/yii2-params-access-within-local-config-file-in-common-directory –