Zend Framework 2 Service in View Helper

rafaame picture rafaame · Jan 6, 2014 · Viewed 13.2k times · Source

I need to write a view helper that gets a service and do something with it. I successfully implemented the view helper to have access to the service locator. The problem is that the service I want to get is not being found through the service locator when the __invoke method is called.

The view helper code:

<?php

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper,
    Zend\ServiceManager\ServiceLocatorAwareInterface,

    Application\Model;

class LoggedCustomer extends AbstractHelper implements ServiceLocatorAwareInterface
{

    use \Zend\ServiceManager\ServiceLocatorAwareTrait;

    public function __invoke()
    {

        $model = new Model\Customer($this->getServiceLocator());

        return $model->getCurrent();

    }

}

A snippet of the model code:

namespace Application\Model;

use Application\Entity,
    Andreatta\Model\Base as Base;

class Customer extends Base
{

    /**
     * 
     * @return Zend\Authentication\AuthenticationService
     */
    public function getAuthService()
    {

        $serviceLocator = $this->getServiceLocator();

        return $serviceLocator->get('Application\Auth');

    }

    /**
     * 
     * @return Zend\Authentication\Adapter\AdapterInterface
     */
    protected function getAuthAdapter()
    {

        return $this->getAuthService()->getAdapter();

    }

    public function getCurrent()
    {

        $authService = $this->getAuthService();

        if ($authService->hasIdentity())
            return $authService->getIdentity();

        return null;

    }

The snippet from module.config.php:

'service_manager' => array
(

    'factories' => array
    (

        'Application\Auth' => function($sm)
        {

            $authService = $sm->get('doctrine.authenticationservice.application');
            $authService->setStorage( new \Zend\Authentication\Storage\Session('Application\Auth'));

            return $authService;

        },

    ),

),

'view_helpers' => array
(

    'invokables' => array
    (

        'loggedCustomer' => 'Application\View\Helper\LoggedCustomer',

    ),

),

When calling the view helper from any view I get the following:

Zend\View\HelperPluginManager::get was unable to fetch or create an instance for Application\Auth

The weird is that the application is functioning correctly (i.e. this service is being normally used by other parts of the application).

EDIT:

I did some research and I think the only services that I can access through the service manager inside the view helper are the ones registered inside the 'view_manager' section of module.config.php. Does anyone have an idea of how to access the other services?

Answer

Exlord picture Exlord · Jan 6, 2014

$this->getServiceLocator() in view helper can only get u other view helpers you need to use $this->getServiceLocator()->getServiceLocator() to get the application services