Php 如何将条令存储库注入ZF2中的服务
我需要在我的邮政服务中注入我的邮政存储库。我有一个Php 如何将条令存储库注入ZF2中的服务,php,doctrine-orm,zend-framework2,Php,Doctrine Orm,Zend Framework2,我需要在我的邮政服务中注入我的邮政存储库。我有一个PostController,PostEntity,PostServiceInterface和PostRepository 我的帖子库包含DQL,其中包含的方法有findAll(),find($id),等等 在我的PostServiceInterface中,我有一些方法,如find,findAll 现在我想访问存储库以从我的服务中获得结果。我不想直接在服务中编写查询。我尝试使用DI将服务注入到\uu构造中,但这不起作用 有人能举例说明如何做到这一
PostController
,PostEntity
,PostServiceInterface
和PostRepository
我的帖子库包含DQL,其中包含的方法有findAll()
,find($id)
,等等
在我的PostServiceInterface
中,我有一些方法,如find
,findAll
现在我想访问存储库以从我的服务中获得结果。我不想直接在服务中编写查询。我尝试使用DI将服务注入到\uu构造中,但这不起作用
有人能举例说明如何做到这一点吗
我将Zend Framework 2与DoctrineORMModule一起使用。最好的方法是编写一个定制的PostServiceFactory
,通过构造函数注入将PostRepository
注入PostService
例如:
<?php
namespace Application\Service\Factory;
use Application\Service\PostService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class PostServiceFactory implements FactoryInterface
{
/**
* Creates and returns post service instance.
*
* @param ServiceLocatorInterface $sm
* @return PostService
*/
public function createService(ServiceLocatorInterface $sm)
{
$repository = $sm->get('doctrine.entitymanager.orm_default')->getRepository('Application\Entity\PostService');
return new PostService($repository);
}
}
最后,在module.config.php
中,还需要在service manager配置中注册工厂:
'service_manager' => array(
'factories' => array(
'Application\Service\PostService' => 'Application\Service\Factory\PostServiceFactory',
)
)
现在,您可以通过控制器中的服务定位器获得售后服务
,如下所示:
<?php
namespace Application\Service;
use Application\Repository\PostRepository;
class PostService
{
protected $repository;
public function __construct(PostRepository $repository)
{
$this->repository = $repository;
}
}
$postService = $this->getServiceLocator()->get('Application\Service\PostService');
PostRepository
将自动注入我们在工厂编写的返回服务实例。这真的是ZF di容器需要采用的方法吗?Symfony容器允许您使用实体管理器定义工厂服务,然后对其调用getRepository。不需要硬编码的售后服务工厂。似乎很奇怪,ZF没有类似的东西。@Cerad,使类依赖于EntityManager
也是可能的,但这不是一个好的设计。Ivke说该服务需要一个ObjectRepository
,因此您还应该注入这个类,而不是某个父类。如果您注入了EntityManager
,您仍然不确定EntityManager
是否能够真正交付正确的存储库类…@Wilt,我不是建议注入实体管理器。我的评论是,在Symfony中,您可以将存储库定义为服务,然后像任何其他依赖项一样根据需要进行注入。根本不需要PostServiceFactory类。在这里查看Symfony中服务定义的示例:@cerad在zf2中肯定存在其他解决方案,如初始化器和委托器工厂。初始化器执行setter注入(如您提到的答案和symfony),但是它有一个较小的性能缺陷,因为服务定位器检查每个服务实例以注入必要的依赖项。symfony中是否存在用于构造函数注入的内置解决方案?