如何在 ZF2 View Helper 中使用 toRoute

How To Use toRoute in ZF2 View Helper

我想在我的视图助手中使用 toRoute 或重定向控制器插件。我知道 View helpers 扩展了视图层的功能,并且可以在我们的整个应用程序中重用。控制器插件扩展了控制器层的功能。但我想要任何其他解决方案来做到这一点。

这是我的视图助手:

<?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'];*/
    }
}

?>

在上面的代码中,行:

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

确实不起作用,我也尝试了几种方法来实现它,但没有任何帮助。

我自己搞定了。我们可以获取控制器插件管理器服务,然后使用任何插件。

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