我试图在zf2中创建一个简单的服务,我可以在viewhelper中使用它
步骤1。 我在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()
{
}
}
第2步 我在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);
});
}
第三步: 最后我在我的视图中帮助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;
}
}
步骤4 然后我在这样的视图中调用我的测试视图助手。
$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:
我错过了什么?