我需要为 Zend 框架的两个 Controller 功能创建一个服务层,以便将服务与 Controller 解耦。
最佳答案
您将需要使用 ServiceManager (SM) 才能使其正常工作。
这只是我如何做到这一点的一个例子:
在您的ModuleName/src/ModuleName/中创建一个名为Service的文件夹并创建您的ExampleService.php,示例:
namespace ModuleName\Service;
class ExampleService
{
public function SomeFunctionNameHere()
{
echo 'Hello World';
}
}
现在编辑您的 Module.php 并将服务层添加到您的可调用对象中,IE:
public function getServiceConfig()
{
return array(
'invokables' => array(
'ModuleName\Service\ExampleService' => 'ModuleName\Service\ExampleService',
),
);
}
现在编辑您的 ModuleNameController.php
protected $service_example;
public function indexAction()
{
$service = $this->getServiceExample()->SomeFunctionNameHere();
}
private function getServiceExample()
{
if (!$this->service_example) {
$this->service_example = $this->getServiceLocator()->get('ModuleName\Service\ExampleService');
}
return $this->service_example;
}
这应该可以帮助您入门。
关于zend-framework2 - 如何在zend框架二中创建服务层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17376453/