Zend Framework 2 Service Manager Dependency Injection - dependency-injection

My application is a collection of POPO's and I'm trying to wire these POPO's up using the Zend Framework 2 Service Manager.
To illustrate my problem, take the following example:
$config = array(
'services' => array(
'my.app.serviceA' => new \My\App\Services\ServiceA(),
'my.app.serviceB' => new \My\App\Services\ServiceB(),
'my.app.manager.task' => new \My\App\Manager\TaskManager(),
),
);
My TaskManager class looks something like this:
class TaskManager {
protected $serviceA;
protected $serviceB;
public function setServiceA( \My\App\Service\ServiceA $serviceA )
{
$this->serviceA = $serviceA;
}
public function setServiceB( \My\App\Service\ServiceB $serviceB )
{
$this->serviceB = $serviceB;
}
}
As you can see, the TaskManager class has dependencies on both ServiceA and ServiceB. How do inject those services into my.app.manager.task using the Service Manager configuration using the service names defined for both ServiceA and ServiceB?
UPDATE:
I'm beginning to believe that I shouldn't be using the ServiceManager component for my purposes at all but that I should be using the Zend DI component instead.
I get the impression that the ServiceManager is a ZF2 "framework" component whereas Zend\DI seems to be more of a generic all purpose DiC. Hence, this might be the reason of ServiceManager's tied relationship with the MVC and ModuleManager components (which also seem to be "framework" components).
Maybe someone could clarify?

in module.config.php The Service Manager can be configured in 7 different ways:
return array(
// instantiate the class for you when needed
'invokables' => array(
'commentController' => '\Comment\Controller\CommentController';
),
// Aliasing a name to a known service name
'aliases' => array(
'Comment\Service' => 'commentService';
),
// configure the instance of the object
'factories' => array(
'commentController' => function ($sm) {
$locator = $sm->getServiceLocator();
$controller = $locator->get('commentController');
$controller->setCommentService($locator->get('Comment\Service'));
return $controller;
}
),
// register already instantiated objects
'services' => array(
'commentController' => new \Comment\Controller\CommentController(),
),
//factory instance that can create multiple services based on the name supplied to the factory.
'abstract_factories' => array(
'SomeModule\Service\FallbackFactory',
),
// initialize the service whenever service created
'initializers' => array(
function ($instance, $sm) {
if ($instance instanceof \Comment\Controller\CommentController){
$instance->setCommentService($sm->get('Comment\Service'));
}
}
),
// indicating whether or not a service should be shared
'shared' => array(
'commentController' => false,
),
);
and in Module.php
public function getControllerConfig() {
return array(
'factories' => array(
'commentController' => function ($sm) {
$controller = new \Comment\Controller\CommentController();
$locator = $sm->getServiceLocator();
$controller->setCommentForm($locator->get('commentForm'));
$controller->setCommentService($locator->get('commentService'));
return $controller;
}
)
);
}
and simple use in controller :
$commentService = $this->serviceLocator->get('Comment\Service');
you put this in getter or in init() method
ZF2's New Controller::init() :: phly, boy, phly

in Controller ;
$yourService = $this->getServiceLocator()->get('your_service_alias');
in View Helper :
you should send in from Module.php by constructor of viewHelper
public function getViewHelperConfig() {
return array(
'factories' => array(
'loginHelper' => function($sm) {
return new LoginHelper($sm);
}
)
}
in a calss
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
public class UseCaseBO implements ServiceLocatorAwareInterface {
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator() {
return $this->serviceLocator;
}
// now instance of Service Locator is ready to use
public function someMethod() {
$table = $this->serviceLocator->get('your_service_alias');
//...
}
}

for me, the best way is to create a class factory and use the factoryInterface, like this :
return array(
'service_manager' => array(
'factories' => [
'Task' => 'Application\TaskFactory',
],
'invokables' => array(
'Task'=> 'Application\Task',
'ServiceA'=> 'Application\ServiceA',
'ServiceB' => 'Application\ServiceB'
)
),
);
And a factory class :
class TaskFactory implements FactoryInterface {
/** #var ServiceLocatorInterface $serviceLocator */
var $serviceLocator;
public function createService(ServiceLocatorInterface $serviceLocator) {
$sl = $this->serviceLocator = $serviceLocator;
// you can get your registered services
$serviceA = $sl->get('ServiceA');
$serviceB = $sl->get('ServiceB');
// You can build your class using the class loader
$task = new Application\Task();
// Or the Service Locator Again
$task = $sl->get('Task');
return $task;
}
}
You can implement the factory interface on your Task class. I prefer to have control on what I'm building.

Related

Zend Framework 2 not loading config from mail.local.php

I am trying to get config smtp from mail.local.php, i did tried ServiceLoader getServiceLoader method, but I am unable to find a way to get configurations in my helper class:
What would be the best way to get autoload\mail.local.php,
namespace Helpers;
use Zend\Mail;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
class SendEmail
{
public static function email($to = '', $recipientName = '', $template = '')
{
$transport = new SmtpTransport();
// $options = new SmtpOptions(array(
// 'name' => 'smtp.mailtrap.io',
// 'host' => 'smtp.mailtrap.io',
// 'port' => 2525,
// 'connection_class' => 'crammd5',
// 'connection_config' => array(
// 'username' => 'f11f5a55fdfbf5',
// 'password' => '7780e1e7ee1cc5',
// ),
// ));
$mail = new Mail\Message();
$html = new \Zend\Mime\Part($template);
$html->type = 'text/html';
$body = new \Zend\Mime\Message;
$body->setParts(array($html));
$mail->setBody($body);
$mail->setFrom('admin#fonedoctors.com', 'Admin FoneDoctors');
$mail->addTo($to, $recipientName);
$mail->setSubject('Unpaid Invoices');
$transport->setOptions($options);
$transport->send($mail);
}
}
If you have your configuration file in /autoload/mail.local.php the configuration will have already been merged together as part of the ZF bootstrapping process. The merged module configuration can then be fetched from the service manager using $serviceManager->get('config');
To inject this configuration into your SendEmail class, you should ideally create a new factory.
class SendEmailFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('config'); // all merged module configuration
$emailOptions = isset($config['my_email_config_key'])
? $config['my_email_config_key']
: [];
return new SendEmail($emailOptions);
}
}
You will also need to register the service with the service manager :
'service_manager' => [
'factories' => [
SendEmail::class => SendEmailFactory::class,
],
],
And update the SendEmail class to accept the options via the constructor.
class SendEmail
{
private $options;
public function __construct(array $options)
{
$this->options = $options;
}
// ...
}

How to include EntityManager in ZendFramework 2 AbstractValidator

I have a custom validator, extending Zend AbstractValidator. The thing is, i want to include Doctrine EntityManager, but i keep failing! I tried to make a Factory for my Validator, but it doesn't seem to work. Help!! What am I doing wrong?
Validator:
$this->objectRepository stays empty, while i expect content.
namespace Rentals\Validator;
use Rentals\Response;
use Zend\Validator\AbstractValidator;
use Zend\Stdlib\ArrayUtils;
class ExistentialQuantification extends AbstractValidator
{
const NO_ENTITY_ID = 'noEntityId';
const ENTITY_NOT_FOUND = 'entityNotFound';
const INVALID_ID = 'invalidId';
protected $messageTemplates = [
self::NO_ENTITY_ID => 'The input does not contain an entity id.',
self::ENTITY_NOT_FOUND => 'The entity could not be found.',
self::INVALID_ID => 'The input does not contain an entity id.',
];
protected $objectRepository;
public function __construct(array $options)
{
$this->objectRepository = $options['object_repository'];
parent::__construct($options);
}
public function isValid($value)
{
if ($value === null) {
return true;
}
if (! isset($value->id)) {
$this->error(self::NO_ENTITY_ID);
return false;
}
$entityClass = $this->getOption('entity_class');
$controller = new Controller();
$entity = (new FactoryInterface)(EntityManager::class)->find($entityClass, $entity->id);
if (! $entity instanceof $entityClass) {
$this->error(self::ENTITY_NOT_FOUND);
return false;
}
if (! $entity->getId()) {
$this->error(self::NO_ENTITY_ID);
return false;
}
return true;
}
}
Factory:
namespace Rentals\Validator;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\MutableCreationOptionsInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\ArrayUtils;
class ExistentialQuantificationFactory implements FactoryInterface, MutableCreationOptionsInterface
{
protected $options = [];
public function setCreationOptions(array $options)
{
$this->options = $options;
}
public function createService(ServiceLocatorInterface $serviceLocator)
{
if (! isset($this->options['object_manager'])) {
$this->options['object_manager'] = 'doctrine.entitymanager.orm_default';
}
$objectManager = $serviceLocator->get($this->options['object_manager']);
$objectRepository = $objectManager->getRepository($this->options['entity_class']);
return new ExistentialQuantification(ArrayUtils::merge(
$this->options, [
'objectManager' => $objectManager,
'objectRepository' => $objectRepository
]
));
}
}
Module config:
<?php
return [
'service_manager' => [
'factories' => [
'Rentals\\Validator\\ExistentialQuantification' => 'Rentals\\Validator\\ExistentialQuantificationFactory'
]
]
];
?>
What if you change your config entry like the following example?
return [
'validators' => [
'factories' => [
ExistentialQuantification::class => ExistentialQuantificationFactory::class,
],
],
];
This change will result in further changes for your factory, because the service locator for the entity manager differs from the one you injected.
namespace Application\Validator\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\MutableCreationOptionsInterface;
use Zend\ServiceManager\MutableCreationOptionsTrait;
use Zend\ServiceManager\ServiceLocatorInterface;
class ExistentialQuantificationFactory implements FactoryInterface, MutableCreationOptionsInterface
{
use MutableCreatinOptionsTrait;
public function createService(ServiceLocatorInterface $serviceLocator)
{
$parentLocator = $serviceLocator->getServiceLocator();
if (! isset($this->creationOptions['object_manager'])) {
$this->creationOptions['object_manager'] = 'doctrine.entitymanager.orm_default';
}
$objectManager = $parentLocator->get($this->creationOptions['object_manager']);
$objectRepository = $objectManager->getRepository($this->creationOptions['entity_class']);
return new ExistentialQuantification(ArrayUtils::merge(
$this->options, [
'objectManager' => $objectManager,
'objectRepository' => $objectRepository
]
));
}
}
What I 've done here? First I implemented the MutableCreationOptionsTrait class. This trait implements the needed functions for working with creation options. But this is just a little hint for avoiding unnecessary work.
Because of setting the validator class as validator in the config, we have to use the parent service locator for getting the entity manager. The inherited service locator just provides access to validators.
Now you can try to access your validator in your controller like in the following examaple.
$validator = $this->getServiceLocator()
->get('ValidatorManager')
->get(ExistentialQuantification::class, [
'entity_class' => YourEntityClass::class,
]);
\Zend\Debug\Debug::dump($validator, __METHOD__);
The validator manager should return your validator so that you can test it.

Error on Injecting dependencies into your ZF2 controllers

Hi I am having errors trying to inject dependencies on my controllers.
Warning: Missing argument 1 for User\Controller\LoginController::__construct(), called in /var/www/html/engsvc_dev/vendor/zendframework/zendframework/library/Zend/ServiceManager/AbstractPluginManager.php on line 170 and defined in /var/www/html/engsvc_dev/module/User/src/User/Controller/LoginController.php on line 23
Module.php
public function getControllerConfig(){
return array(
'factories' => array(
'Login' => function ($sm) {
$locator = $sm->getServiceLocator();
$controller = new LoginController($locator->get("Config"));
return $controller;
},
),
);
}
Controller
class LoginController extends AbstractActionController{
protected $globalConfig;
protected $UserModuleSetup;
public function __construct($config){
}
module.config.php
"invokables" => array(
"User" => "User\Controller\LoginController",
"Login" => "User\Controller\LoginController"
),
Module.php
public function getControllerConfig(){
return array(
'factories' => array(
'Login' => function ($sm) {
$locator = $sm->getServiceLocator();
$controller = new User\Controller\LoginController($locator->get("Config"));
return $controller;
},
),
);
}
Controller
class LoginController extends AbstractActionController{
protected $globalConfig;
protected $UserModuleSetup;
public function __construct($config){
}
module.config.php
"invokables" => array(
"User" => "User\Controller\LoginController",
),

ZF2: How to catch exceptions thrown by a view helper automatically

I have a some view helpers throwing exceptions on error. That's ok for development, but for production I would like to configure PhpRenderer to catch and log the exception without braking the hole view file to render - simply return nothing.
The PhpRenderer has the method:
public function __call($method, $argv)
{
if (!isset($this->__pluginCache[$method])) {
$this->__pluginCache[$method] = $this->plugin($method);
}
if (is_callable($this->__pluginCache[$method])) {
return call_user_func_array($this->__pluginCache[$method], $argv);
}
return $this->__pluginCache[$method];
}
Is it enough to overwrite this method?
How can I replace the PhpRenderer with my own?
You can do it by writing your own view strategy.
First, register your new strategy in the configuration.
return array(
'factories' => array(
'MyStrategy' => 'Application\ViewRenderer\StrategyFactory',
)
'view_manager' => array(
'strategies' => array(
'MyStrategy'
),
),
);
Then, create your own strategy
namespace Application\ViewRenderer;
use Zend\View\Strategy\PhpRendererStrategy;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
class StrategyFactory implements FactoryInterface
{
public function createService (ServiceLocatorInterface $serviceLocator)
{
$renderer = new Renderer ();
return new Strategy ($renderer);
}
}
and renderer.
namespace Application\ViewRenderer;
use Zend\View\Renderer\PhpRenderer;
class Renderer extends PhpRenderer
{
public function render($nameOrModel, $values = null) {
// this is just an example
// the actual implementation will be very much like in PhpRenderer
return 'x';
}
}

View Module Exception Strategy

I have a controller that saves some data.
$pat = $sm->get('Tables\PaymentAttemptsTable');
$pat->save($post);
The module configuration has the following config:
public function onBootstrap(EventInterface $e)
{
$em = $e->getApplication()->getEventManager();
$em->attach('dispatch', array($this, 'loadConfiguration' ), 100);
}
public function loadConfiguration(EventInterface $e)
{
$sm = $e->getApplication()->getServiceManager();
//if this module
$exceptionstrategy = $sm->get('ViewManager')->getExceptionStrategy();
$exceptionstrategy->setExceptionTemplate('error/inserterror');
}
On the PaymentAttemptsTable module confi I have a similar strategy like this.
public function onBootstrap(EventInterface $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach('dispatch', array($this, 'loadConfiguration' ), 100);
}
public function loadConfiguration(EventInterface $e)
{
$sm = $e->getApplication()->getServiceManager();
//if this module
$exceptionstrategy = $sm->get('ViewManager')->getExceptionStrategy();
$exceptionstrategy->setExceptionTemplate('error/saveerror');
}
On each one I have a view confi like this.
return array(
'view_manager' => array(
'exception_template' => 'error/index',
'template_map' => array(
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
);
The thing is that when I do
throw new SaveError('Table must be a string or instance of TableIdentifier.');
on the PaymentAttemptsTable class I get the template from the controller and not form the table class, is there a way to fix this?
if you look at the Controller and View Models section of
http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html
It shows you how to load different view templates, what you will need to do is change the view template to the one that needs to be loaded in the PaymentAttemptsTable class. This will need to be done in the calling controller.
Example from Zend.com
namespace Foo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BazBatController extends AbstractActionController
{
public function doSomethingCrazyAction()
{
$view = new ViewModel(array(
'message' => 'Hello world',
));
$view->setTemplate('foo/baz-bat/do-something-crazy');
return $view;
}
}

Resources