zf2创建简单服务并通过viewhelper进行访问 [英] zf2 Creation of simple service and access it through viewhelper
问题描述
我正在尝试在zf2中创建一个简单的服务,我可以在viewhelper中使用该服务
I am trying to create a simple service in zf2 which I can access using in viewhelper
第1步.我在src/Application/Service/Service1.php中创建了一个类,如下所示:
Step1. I have craeted a class in src/Application/Service/Service1.php as follow
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()
{
}
}
第2步,我在module.php文件中进行了如下设置.
Step2 I set this up in module.php file as below.
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 test()方法中得到它,II注释此行$this->sm->get('Application\Service\Service1');
没有错误,服务中肯定缺少某些东西吗?
Step3 finally I am geting it in my view helper src/Application/View/Helper/Abc.php test() method like this, I I comment this line $this->sm->get('Application\Service\Service1');
there is no error, there must be something which I am missing in service?
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 ,然后我在这样的视图之一中调用我的测试视图助手.
Step4 then I am calling my test view helper in one of view like this.
$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:
我想念什么?
推荐答案
在以下方法中更改行$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;
}
}
这篇关于zf2创建简单服务并通过viewhelper进行访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!