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');
这不是一个完美的解决方案,但它应该可以工作。