可调用对象应用于实例化一个简单对象,该对象不需要构造函数中的任何其他依赖项等。
当实例化对象背后有一些更复杂的逻辑时,您应该使用工厂。将代码移入工厂将节省您在需要返回对象时复制代码。
工厂示例:
'factories' => array(
'Application\Acl' => 'Application\Service\AclFactory',
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;
}
}
如果你想要返回一个简单的类/对象,那么你可以只使用一个可调用的,因为不需要样板代码来获取对象。
'invokables' => array(
'MyClass' => 'Application\Model\MyClass',
另一个带有控制器的示例:
如果您有一个简单的控制器,没有必需的依赖项,请使用可调用的:
'invokables' => array(
'index' => 'Mis\Controller\IndexController',
但有时您希望在实例化控制器时向控制器添加额外的依赖项:
'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;
},