【问题标题】:[Symfony 2]Use Doctrine into a service[Symfony 2]在服务中使用 Doctrine
【发布时间】:2015-08-01 22:15:34
【问题描述】:

我在我的项目中创建了一个新服务。该服务是用 XML 配置的。 我想使用 EntityManager 来检索服务中的 som 数据,但我无法将 Doctrine “连接”到我的服务。 目前,我有这个代码:

services.xml

<service id="SiteService.search" class="Site\ProductBundle\Search\SphinxSearch" factory-service="doctrine.orm.entity_manager" factory-method="getRepository">
<argument>Site\ProductBundle\Entity\Product</argument>
</service>

SphinxSearch.php

namespace Dada\FilmsBundle\Search;
use Symfony\Component\DependencyInjection\ContainerAware;
class DadaSearch extends ContainerAware{
    //Some stuff
    public function fullNoPrivateByTitle($query){
        //Call $this->getResultsFromId($idlist);
    }
    private function getResultsFromId($idlist){
    $doctrine = $this->container->get('doctrine')->getManager()->getRepository('SiteProductBundle:Product');
    //Rest of the method
    }

使用这段代码,我遇到了一个奇怪的错误。似乎 Symfony 认为我的服务是一种新的教义:

未定义的方法“fullNoPrivateByTitle”。方法名必须开始 使用 findBy 或 findOneBy! 500内部服务器错误 - 坏方法调用异常

有人可以帮我配置我的服务吗? 非常感谢。

【问题讨论】:

  • 看看这个post它可以帮到你
  • 这篇文章对你有帮助吗??

标签: xml symfony doctrine-orm doctrine


【解决方案1】:

您的实现在几个不同的方面感到困惑。

  1. factory-method 返回的对象必须与class 属性中定义的类型相同 - 所以是从Doctrine\ORM\EntityRepository 继承的(这是您的“奇怪错误”的来源)
  2. 定义一个服务然后让它扩展ContainerAware 是没有意义的。定义服务的重点是通过配置注入依赖项——而不是在运行时从容器中提取它们。
  3. 不一致的命名 - 您的服务引用 Site\ProductBundle\Search\SphinxSearch 但您的类实际上命名为 Dada\FilmsBundle\Search\DataSearch

注入EntityRepository 有两种选择:在此处尝试使用工厂,或使用expression language

工厂方法应该是这样的(假设正确的存储库是ProductRepository

<service
    id="repository.product"
    class="Site\ProductBundle\Entity\ProductRepository"
    factory-service="doctrine.orm.entity_manager"
    factory-method="getRepository"
>
    <argument>Site\ProductBundle\Entity\Product</argument>
</service>

<service id="SiteService.search" class="Site\ProductBundle\Search\SphinxSearch">
   <argument type="service" id="repository.product"/>
</service>

表达式语法如下所示

<service id="SiteService.search" class="Site\ProductBundle\Search\SphinxSearch">
   <argument type="expression">service('doctrine.orm.entity_manager').getRepository('ProductBundle:Product')</argument>
</service>

然后在你的服务类中

<?php

namespace Site\ProductBundle\Search;

class SphinxSearch
{
    /**
     * @var \Site\ProductBundle\Entity\ProductRepository
     */
    protected $repository;

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

    private function getResultsFromId($idlist) {
        // Do whatever with $this->repository
    }
}

【讨论】:

  • 在 sf 3 - 属性“工厂服务”是不允许的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 2011-12-06
相关资源
最近更新 更多