zend-framework2zend-view

How To Use toRoute in ZF2 View Helper


I want to use toRoute or redirect controller plugin in my view helper. I know View helpers extend functionality on the view layer and are for reusability throughout our application. Controller plugins extend functionality on the controller layer. But I want any other solution to do that.

Here is my view helper:

<?php

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;  
use Zend\ServiceManager\ServiceLocatorInterface;  

class GetSiteSettings extends AbstractHelper implements ServiceLocatorAwareInterface {
    
    protected $serviceLocator;
    
    /**
     * Set the service locator.
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return CustomHelper
     */
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        return $this;
    }
    /**
     * Get the service locator.
     *
     * @return \Zend\ServiceManager\ServiceLocatorInterface
     */
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }
    
    public function __invoke()
    {
        $redirect = $this->redirect()->toRoute('my_account');
        /*$sm   = $this->getServiceLocator()->getServiceLocator();
        $config = $sm->get('Config');
        return  $config['site_settings'];*/
    }
}

?>

In the above code, the line:

$redirect = $this->redirect()->toRoute('my_account');

is really not working and I also tried several things to achieve it, but nothing helped.


Solution

  • I've got it at my own. We can get the controller plugin manager service and then use any plugin.

    $sm       = $this->getServiceLocator()->getServiceLocator();
    $redirect = $sm->get('ControllerPluginManager')->get('redirect');
    $redirect->toRoute('my_account')