gpt4 book ai didi

zend-framework2 - 多个 Controller 的单一工厂?

转载 作者:行者123 更新时间:2023-12-04 07:08:50 24 4
gpt4 key购买 nike

简而言之,我的问题是:我可以为多个 Controller 使用一个工厂吗?

更多细节:

我在/config/autoload/global.php 中有一些全局非模块特定设置,如下所示:

return array(
'settings' => array(
'setting_a' => 'foo',
'setting_b' => 'bar'
),

// More ZF default configuration ...
);

现在我想让这些设置在每个 Controller 中都可以访问,而无需调用 $this->getServiceLocator()->get('config')。每时每刻。

所以我的想法是引入一个类属性 $settings在我的 AbstractController它被注入(inject)了配置数组。我试图直接在 AbstractController 的构造函数中获取配置.然而 getServiceLocator()当时似乎还没有准备好并返回 NULL。

我可以为每个 Controller 构建 Controller 工厂并注入(inject)如下设置:
class ControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator) {
$config = $serviceLocator->get('config');
return new \MyModule\Controller\MyController($config['settings']);
}
}

但它会一遍又一遍地相同。所以我的问题是:我可以为多个 Controller 使用一个工厂吗?

在我的 module.config.php 中,我可以为多个 Controller 指定一个工厂类:
return array(
'controllers' => array(
'factories' => array(
'MyModule\Controller\MyControllerA' => 'MyModule\Factory\ControllerFactory',
'MyModule\Controller\MyControllerB' => 'MyModule\Factory\ControllerFactory',
'MyModule\Controller\MyControllerC' => 'MyModule\Factory\ControllerFactory',
)
),
);

但是在工厂中,我需要手动返回实际的 Controller 对象(参见上面的示例),这当然只适用于每个 Controller 的一个工厂。

希望,我把我的问题说清楚了。

2013 年 3 月 24 日更新:

尽管我首先通过创建一个初始化程序来遵循建议的解决方案,但我从来没有真正喜欢将它仅用于配置注入(inject)。

所以我一直在挖掘并最终创建了一个 Controller 插件来接收设置。

该插件的代码如下所示:
use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class Settings extends AbstractPlugin
{
protected $settings;

public function __invoke()
{
$config = $this->getController()->getServiceLocator()->get('Config');

if (isset($config['settings']) && is_array($config['settings'])) {
$this->settings = $config['settings'];
}

return $this->settings;
}
}

在 module.config.php 中添加插件后
'controller_plugins' => array(
'invokables' => array(
'settings' => 'My\Controller\Plugin\Settings',
)
),

我只需调用 $this->settings() 即可轻松访问 Controller 中的设置。 .希望这对任何人都有帮助。

最佳答案

您可以尝试附加一个初始化程序,然后在创建 Controller 时根据已知的初始化程序检查实例。如果实例匹配给定的接口(interface)或抽象类,那么您可以应用一些通用逻辑。

我没有用 Controller 测试过这种方法,但考虑到 ControllerLoader 是一种 ServiceManager/ServiceLocator,理论上它应该可以工作。

'controllers' => array (
'initializers' => array(
'MyApplication\Controller\Initializer'
)
),

然后初始化器看起来像:
class Initializer implements InitializerInterface
{
public function initialize($instance, ServiceLocatorInterface $serviceLocator)
{
if (!$instance instanceof MyControllerInterface)
{
return;
}

// Do something for this instance
}
}

关于zend-framework2 - 多个 Controller 的单一工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13000752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com