Za pomocą invokałów należy utworzyć obiekt sinmple, który nie wymaga żadnych innych zależności itp. W kontrercie.
Powinieneś użyć fabryki, gdy jest za mało skomplikowanej logiki za instancją obiektu. Przeniesienie kodu do fabryki uratuje ci duplikowanie kodu, gdy tylko będziesz potrzebować ponownie obiektu. Przykładem
fabryczne:
'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;
}
}
Jeśli chcesz z powrotem prostą klasę/obiekt wtedy można po prostu użyć invokable, jak nie ma kod płyty kotła potrzebny do odzyskania obiektu.
'invokables' => array(
'MyClass' => 'Application\Model\MyClass',
inny przykład, z kontrolerami:
Jeśli masz prosty kontroler, bez wymagane na zależnościach, użyj invokable:
'invokables' => array(
'index' => 'Mis\Controller\IndexController',
Ale czasami chcesz dodać kolejne zależności do kontroler, gdy go tworzysz:
'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;
},
Jeśli mam fabrykę to obowiązkowe jest wykorzystanie Fa ctoryInterface? Czy to jest zła forma, jeśli wykonuję konstruktor klasy Factory '__invoke'? – Erik