Php 如何在zend framework 2中创建工厂?
在我的Php 如何在zend framework 2中创建工厂?,php,class,zend-framework2,factory-pattern,servicemanager,Php,Class,Zend Framework2,Factory Pattern,Servicemanager,在我的Module.php中,我有一些空闲方法,我想将它们移动到工厂类中,这样我就不会把模块类弄得乱七八糟了: public function getControllerConfig() { return array( 'factories' => array( 'account-index' => function ($controllerManager) { $serviceManager = $co
Module.php
中,我有一些空闲方法,我想将它们移动到工厂类中,这样我就不会把模块类弄得乱七八糟了
:
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;
}
)
);
}
现在我有:
我应该把这个工厂类
放在哪里,可能放在工厂
文件夹中
有什么想法吗?我通常把我的工厂放到。/module/yourmodule/src/yourmodule/Factory
中
在。/module/yourmodule/config/module.config.php
中,您必须按照如下方式配置服务管理器:
'service_manager' => array(
'factories' => array(
'yourfactory' => 'yourmodule\Factory\yourfactory',
),
),
在yourfactory.php
中,您必须实现FactoryInterface并设置服务定位器。完成此操作后,您应该能够以控制器、窗体等的常规方式调用服务
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
中定义函数。在您的控制器中,您可以调用这样的函数:so$serviceManager->get('yourfactory')->yourfunction(yourarguments)代码>差不多了。工厂应仅返回特定的服务类别。你不应该像使用服务或模型一样使用工厂。i、 e:createService(){$db=$sl->get('db');return=newgateway($db);}