在我的 Module.php
中,我有一些休闲方法,我想将它们移动到 factory class
中,这样我就不会弄乱 Module class
:
public function getControllerConfig()
{
return array(
'factories' => array(
'account-index' => function ($controllerManager) {
$serviceManager = $controllerManager->getServiceLocator();
$accountService = $serviceManager->get('account-service');
return new Controller\IndexController($accountService);
}
)
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'account-service' => function ($serviceManages) {
return new Service\Account;
}
)
);
}
现在我有:
我应该把这个 factory class
放在哪里,也许在 Factory
文件夹中?
有什么想法吗?
最佳答案
我通常将我的工厂放入../module/yourmodule/src/yourmodule/Factory
。
在您的 ../module/yourmodule/config/module.config.php
中,您必须像这样配置您的 service_manager:
'service_manager' => array(
'factories' => array(
'yourfactory' => 'yourmodule\Factory\yourfactory',
),
),
在 yourfactory.php
中,您必须实现 FactoryInterface 并设置服务定位器。完成此操作后,您应该能够以通常的方式为 Controller 、表单等调用服务。
namespace Application\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class yourfactory implements FactoryInterface
{
private $config;
private $serviceLocator;
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $servicelocator->get('Your\Service');
}
之后,您可以在 yourfactory.php
中定义函数。在您的 Controller 中,您可以像这样调用函数 $serviceManager->get('yourfactory')->yourfunction(yourarguments);
关于php - 如何在 zend 框架 2 中创建工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18865569/