如何使用工厂注册View帮助程序?
View\Helper\GenerateAnchor::class => GenerateAnchorFactory::class,
答案 0 :(得分:6)
我猜你只需要配置文件中的设置,但我会在Zend 3中显示注册视图助手的完整之路
首先,我们需要查看助手:
namespace MyNamespace\View\Helper;
use Zend\View\Helper\AbstractHelper;
class TestViewHelper extends AbstractHelper
{
public function __invoke()
{
// your code...
}
}
如果我们需要注入一些依赖项,那么我们需要创建自定义工厂,但是如果我们的视图助手不需要其他服务/类,那么我们可以跳过这一步
namespace MyNamespace\Factory\View\Helper;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use MyNamespace\View\Helper\TestViewHelper;
class TestViewHelperFactory implements FactoryInterface
{
/**
*
* @param ContainerInterface $container
* @param string $requestedName
* @param null|array $options
* @return TestViewHelper
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$class = $requestedName ? $requestedName : TestViewHelper::class;
$auth = $container->get('MyCustomAuth');
$viewHelper = new $class($auth);
return $viewHelper;
}
/**
* Provided for backwards compatibility; proxies to __invoke().
*
* @param ContainerInterface|ServiceLocatorInterface $container
* @return TestViewHelper
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container, TestViewHelper::class);
}
}
最后一步是在module.config.php
'view_helpers' => [
'aliases' => [
'viewPlugin' => View\Helper\TestViewHelper::class,
],
'factories' => [
View\Helper\TestViewHelper::class => InvokableFactory::class // Or use your own factory
]
],
并且......在我们的视图模板中,我们可以像这样使用它:
<强> index.phtml 强>
<?php echo $this->viewPlugin(); ?>