Pat*_*cow 7 php class factory-pattern zend-framework2 servicemanager
在我的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;
}
)
);
}
Run Code Online (Sandbox Code Playgroud)
现在我有:
我把它放在哪里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',
),
),
Run Code Online (Sandbox Code Playgroud)
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');
}
Run Code Online (Sandbox Code Playgroud)
之后你可以在你的中定义函数yourfactory.php.在您的Controller中,您可以调用这样的函数$serviceManager->get('yourfactory')->yourfunction(yourarguments);