简体   繁体   English

如何在ZF2中将doctrine存储库注入服务

[英]How to inject doctrine repository to service in ZF2

I need to inject my post repository in my post service. 我需要在我的邮政服务中注入我的帖子库。 I have a PostController , PostEntity , PostServiceInterface and PostRepository . 我有一个PostControllerPostEntityPostServiceInterfacePostRepository

My post repository contains DQL with methods like findAll() , find($id) , etc... 我的帖子库包含DQL和findAll()find($id)等方法...

In my PostServiceInterface I have some methods like find , findAll . 在我的PostServiceInterface我有一些方法,比如findfindAll

Now I want to access to repository to get results from my service. 现在我想访问存储库以获取我的服务的结果。 I do not want to write queries directly in service. 我不想直接在服务中编写查询。 I try to inject the service into __construct using DI but that doesn't work. 我尝试使用DI将服务注入__construct但这不起作用。

Can someone provide an example on how to do this? 有人可以提供一个如何做到这一点的例子吗?

I am using Zend Framework 2 with DoctrineORMModule. 我正在使用Zend Framework 2和DoctrineORMModule。

The best way is writing a custom PostServiceFactory to inject PostRepository to the PostService via constructor injection. 最好的办法是写一个自定义PostServiceFactory注入PostRepositoryPostService通过构造函数注入。

For example: 例如:

<?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);
    }
}

You also need to change the PostService 's constructor signature like below: 您还需要更改PostService的构造函数签名,如下所示:

<?php
namespace Application\Service;

use Application\Repository\PostRepository;

class PostService
{
    protected $repository;

    public function __construct(PostRepository $repository)
    {
        $this->repository = $repository;
    }
}

Finally, in your module.config.php you also need to register your factory in the service manager config: 最后,在您的module.config.php您还需要在服务管理器配置中注册您的工厂:

'service_manager' => array(
    'factories' => array(
        'Application\Service\PostService' => 'Application\Service\Factory\PostServiceFactory',
    )
)

Now, you can get the PostService via the service locator in your controller like below: 现在,您可以通过控制器中的服务定位器获取PostService ,如下所示:

$postService = $this->getServiceLocator()->get('Application\Service\PostService');

The PostRepository will be automatically injected into the returned service instance as we coded in our factory. 当我们在工厂编码时, PostRepository将自动注入返回的服务实例中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM