我试图在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()
{
}
}
Run Code Online (Sandbox Code Playgroud)
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);
});
}
Run Code Online (Sandbox Code Playgroud)
Step3最后我在我的视图中帮助src/Application/View/Helper/Abc.php测试()方法就像这样,II注释这行$this->sm->get('Application\Service\Service1');没有错误,必须有一些我在服务中缺少的东西?
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper; …Run Code Online (Sandbox Code Playgroud)