【问题标题】:How to override the native zf2 view helpers with a custom helper如何使用自定义帮助程序覆盖本机 zf2 视图帮助程序
【发布时间】:2014-09-05 08:20:38
【问题描述】:

我想创建一个自定义基本路径帮助器来替换原来的 zf2 基本路径视图帮助器。

所以如果我调用$this->basepath,它将使用我的自定义基本路径而不是原始路径。我不确定这是否可以做到。我希望我的自定义基本路径也扩展原始基本路径类。

我找到了一些关于如何创建自定义助手以及如何在 module.php 或 module.config.php 中注册它们的答案

但是我找不到任何关于如何覆盖原始助手的类似问题!

【问题讨论】:

    标签: model-view-controller view zend-framework2


    【解决方案1】:

    basepath 视图助手的工厂定义在 HelperPluginManager (on line 45) 中声明为硬编码 invokable,但是该定义也在 ViewHelperManagerFactory (line 80 to 93) 中被覆盖,因为 BasePath 视图助手需要 Request 来自 ServiceLocator 的实例:

    $plugins->setFactory('basepath', function () use ($serviceLocator) {
        // ...
    })
    

    我强烈建议使用不同的名称(例如MyBasePath)扩展内置的基本路径帮助程序,而不是尝试覆盖现有的。覆盖该本地助手可能会在以后产生一些意想不到的麻烦(想想使用该助手工作的第 3 方模块)。

    对于您的问题;是的,有可能。

    创建Application\View\Helper\BasePath.php 辅助类,如下所示:

    namespace Application\View\Helper;
    
    use Zend\View\Helper\BasePath as BaseBasePath; // This is not a typo
    
    /**
     * Custom basepath helper
     */
    class BasePath extends BaseBasePath
    {
        /**
         * Returns site's base path, or file with base path prepended.
         */
        public function __invoke($file = null)
        {
            var_dump('This is custom helper');
        }
    }
    

    并在 Module.php 文件的 onBootstrap() 方法中覆盖工厂,如下所示:

    namespace Application;
    
    use Zend\Mvc\MvcEvent;
    use Application\View\Helper\BasePath; // Your basepath helper.
    use Zend\View\HelperPluginManager;
    
    class Module
    {
        /**
         * On bootstrap for application module.
         *
         * @param  MvcEvent $event
         * @return void
         */
        public function onBootstrap(MvcEvent $event)
        {
            $services = $event->getApplication()->getServiceManager();
    
            // The magic happens here
            $services->get('ViewHelperManager')->setFactory('basepath', function (HelperPluginManager $manager) {
                $helper = new BasePath();
                // Here you can do whatever you want with the instance before returning
                return $helper;
            });
        }
    }
    

    现在你可以在任何视图中尝试这样的:

    echo $this->basePath('Bar');
    

    这不是一个完美的解决方案,但它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多