我正在尝试在 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()
{
}
}
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 test() 方法中得到它,我评论这一行$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:
我错过了什么?