将存储库注入 Factory Symfony2 [英] Injecting repositories into Factory Symfony2

查看:55
本文介绍了将存储库注入 Factory Symfony2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Symfony2 框架中的服务注入概念.我有这个设置.存储库、工厂、控制器.我正在尝试将存储库注入工厂以创建供我的控制器处理的对象.

I am learning concept of service injection in Symfony2 framework. I have this set up. Repository, Factory, Controller. I am trying to inject repository into a factory to create objects for my controller to handle.

我设置了一个 services.xml 文件,我试图在其中声明我的服务,我想这就是我出错的地方.

I set up a services.xml file where I am trying to declare my service and i guess this is where i am going wrong.

Fatal error: Uncaught exception 'Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException' with message 'The service "joint.venture.postcode.factory" has a dependency on a non-existent service

我的仓库:

class Postcode {

    private $postcode;
    private $paf;

    public function setPostcode($postcode)
    {
        $this->postcode = $postcode;
    }

    public function getPostcode()
    {
        return $this->postcode;
    }

    public function setPaf($paf)
    {
        $this->paf = $paf;
    }

    public function getPaf()
    {
        return $this->paf;
    }
} 

我的工厂

use Test\Bundle\Repository\Postcode;

class PostcodeFactory
{

    private $postcode;

    public function __construct(
        Postcode $postcode
    ){
        $this->postcode = $postcode;
    }

    public function test()
    {
        return $this->setPostcode('Hello');
    }

} 

我的服务:

<service id="test.postcode.factory"
         class="Test\Bundle\Factory\PostcodeFactory">

        <argument type="service" id="repository.postcode"/>
</service>

任何人都看错了..?

推荐答案

糟糕.看起来@Gerry 打败了我.他使用 xml.哦,好吧.

Oops. Looks like @Gerry beat me to it. And he uses xml. Oh well.

以下是将存储库定义为服务的示例.与大多数事情一样,一旦你做了一些事情,事情就会变得很简单.我使用 yaml 而不是 xml 但概念是一样的.我也喜欢为实体管理器名称取别名,但这不是必需的.

Here is an example of defining a repository as a service. As with most things, it's straight forward once you have done a few. I use yaml instead of xml but the concept is the same. I also like to alias the entity manager name but it's not required.

cerad_user.entity_manager.doctrine:
    alias: doctrine.orm.default_entity_manager

cerad_user.user_repository.doctrine:
    class:  Cerad\Bundle\UserBundle\Entity\UserRepository
    factory_service: 'cerad_user.entity_manager.doctrine'
    factory_method:  'getRepository'
    arguments:  
        - 'Cerad\Bundle\UserBundle\Entity\User'

如果您的所有服务需要的是一个存储库,那么注入一个存储库比注入整个实体管理器更干净.至少在我不那么谦虚的看法中.

If all your service needs is a repository then injecting a repository is cleaner than injecting the entire entity manager. At least in my not so humble opinion.

这篇关于将存储库注入 Factory Symfony2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆