我正在尝试在zf2中创建一个简单的服务,我可以在viewhelper
中使用它Step1。我在src / Application / Service / Service1.php中创建了一个类,如下所示
namespace Application\Service;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class Service1 implements ServiceLocatorAwareInterface
{
public function __construct()
{
}
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
}
public function getServiceLocator()
{
}
}
Step2 我在module.php文件中将其设置如下。
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Service\Service1' => function ($sm) {
return new \Application\Service\Service1($sm);
},
)
);
}
public function onBootstrap($e)
{
$serviceManager = $e->getApplication()->getServiceManager();
$serviceManager->get('viewhelpermanager')->setFactory('Abc', function ($sm) use ($e) {
return new \Application\View\Helper\Abc($sm);
});
}
Step3 最后我在我的视图帮助器src / Application / View / Helper / Abc.php测试()方法这样做,我评论这一行$this->sm->get('Application\Service\Service1');
没有错误,必须有一些我在服务中缺少的东西?
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class Abc extends AbstractHelper
{
protected $sm;
public function test()
{
$this->sm->get('Application\Service\Service1');
}
public function __construct($sm) {
$this->sm = $sm;
}
}
Step4 然后我在这样的一个视图中调用我的测试视图助手。
$this->Abc()->test();
我收到了以下错误。
Fatal error: Call to undefined method Application\Service\Service1::setView() in vendor/zendframework/zendframework/library/Zend/View/HelperPluginManager.php on line 127 Call Stack:
我错过了什么?
答案 0 :(得分:7)
替代方案,仅在PHP 5.4中,没有特定配置,将使用traits:
module.config.php的摘录:
'view_helpers' => array(
'invokables' => array(
'myHelper' => 'Application\View\Helper\MyHelper',
),
MyHelper.php:
<?php
namespace Application\View\Helper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
class HeadScript extends \Zend\View\Helper\MyHelper implements ServiceLocatorAwareInterface
{
use \Zend\ServiceManager\ServiceLocatorAwareTrait;
public function __invoke()
{
$config = $this->getServiceLocator()->getServiceLocator()->get('Config');
// do something with retrived config
}
}
答案 1 :(得分:5)
更改以下方法
中的行$this->sm->getServiceLocator()->get('Application\Service\Service1');
class Abc extends AbstractHelper
{
protected $sm;
public function test()
{
$this->sm->getServiceLocator()->get('Application\Service\Service1');
}
public function __construct($sm) {
$this->sm = $sm;
}
}