Yan*_*hao 11 zend-framework2 service-management
嗨,我是zend框架的新手.试着赶上服务经理.基于zend框架文档,它说:
工厂,一组服务名称/工厂类名称对.工厂应该是实现Zend\ServiceManager\FactoryInterface或可调用类的类.如果您使用的是PHP配置文件,则可以将任何PHP可调用作为工厂提供.
invokables,一组服务名称/类名对.类名应该是可以在没有任何构造函数参数的情况下直接实例化的类.
但我仍然不放弃了解他们之间的不同.什么时候我应该使用可调用的,什么时候我应该使用工厂?使用工厂有什么好处?非常感谢.
And*_*rew 23
应该使用invokable来实例化一个简单的对象,它在contstructor中不需要任何其他依赖项等.
当实例化对象后面有一些更复杂的逻辑时,你应该使用工厂.将代码移动到工厂将节省您在需要对象时复制代码.
工厂示例:
'factories' => array(
'Application\Acl' => 'Application\Service\AclFactory',
Run Code Online (Sandbox Code Playgroud)
AclFactory.php
namespace Application\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Permissions\Acl\Resource\GenericResource;
use Zend\Permissions\Acl\Role\GenericRole;
class AclFactory implements FactoryInterface
{
/**
* Create a new ACL Instance
*
* @param ServiceLocatorInterface $serviceLocator
* @return Demande
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$acl = new \Zend\Permissions\Acl\Acl();
/**
* Here you can setup Resources, Roles or some other stuff.
* If it's complex you can make a factory like this to keep
* the code out of the service config, and it will save you
* having to duplicate the code when ever you need your ACL
*/
return $acl;
}
Run Code Online (Sandbox Code Playgroud)
}
如果你想要一个简单的类/对象,那么你可以使用一个invokable,因为没有需要的样板代码来恢复对象.
'invokables' => array(
'MyClass' => 'Application\Model\MyClass',
Run Code Online (Sandbox Code Playgroud)
另一个带控制器的例子:
如果您有一个简单的控制器,没有需要的依赖项,请使用invokable:
'invokables' => array(
'index' => 'Mis\Controller\IndexController',
Run Code Online (Sandbox Code Playgroud)
但有时您希望在实例化时向控制器添加额外的依赖项:
'factories' => array(
/**
* This could also be added as a Factory as in the example above to
* move this code out of the config file..
*/
//'users' => 'Application\Service\UsersControllerFactory',
'users' => function($sm) {
$controller = new \Application\Controller\UsersController();
$controller->setMapper($sm->getServiceLocator()->get('UserMapper'));
$controller->setForm($sm->getServiceLocator()->get('UserForm'));
return $controller;
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4843 次 |
| 最近记录: |