简体   繁体   English

无法在Symfony中使用自动装配获取Doctrine EntityManager

[英]Cannot fetch the Doctrine EntityManager with autowire in Symfony

Well, I'm going crazy, there's something I don't get with the Symfony (3.3) autowiring stuff. 好吧,我快要疯了,Symfony(3.3)自动装配的东西我没有得到。 I've read those resources : http://symfony.com/doc/current/service_container.html http://symfony.com/doc/current/service_container/3.3-di-changes.html and others that I can't post because I need 10 reputation. 我已经阅读了这些资源: http : //symfony.com/doc/current/service_container.html http://symfony.com/doc/current/service_container/3.3-di-changes.html和其他我无法找到的资源发布,因为我需要10点声望。 I've also read many articles/stackoverflow posts, but with no luck. 我也阅读了许多文章/ stackoverflow帖子,但是没有运气。

I've tried to set up my services, and it almost works, it's just that the EntityManager is null, so I can't call ->getRepository() on it. 我试图设置我的服务,并且几乎可以正常工作,只是EntityManager为null,所以我不能在其上调用->getRepository() The error happens on the line like this in my factory: 该错误发生在我的工厂中,如下所示:

$databaseTournament = $this->em->getRepository('AppBundle:Tournament')
    ->find($tournament);

"Call to a member function getRepository() on null" “在null上调用成员函数getRepository()”

It seems to find the services correctly but never injects the EntityManager in the factory. 似乎可以正确找到服务,但从未在工厂中注入EntityManager。 I've tried to configure things explicitely in the services.yml , but I never managed to make it work. 我尝试在services.yml中显式配置事物,但从未设法使其正常工作。

I'm trying to figure it ou since yesterday, but I'm getting really confused. 从昨天开始,我一直想弄清楚它,但是我真的很困惑。 Could you help me ? 你可以帮帮我吗 ? Thank you in advance ! 先感谢您 ! :) :)

Here are my files : 这是我的文件:

services.yml: services.yml:

parameters:
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
    AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller'
        public: true
        tags: ['controller.service_arguments']

EntryFactory: EntryFactory:

<?php
namespace AppBundle\Factory;

use AppBundle\Entity\Entry;
use AppBundle\Entity\Team;
use AppBundle\Entity\Tournament;
use AppBundle\Exception\InvalidEntryArgumentException;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityNotFoundException;

class EntryFactory
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function createEntry($tournament, $team, $eliminated = false)
    {
        $entry = new Entry();

        if ($tournament instanceof Tournament) {
            $entry->setTournament($tournament);
        }
        elseif (is_int($tournament) && $tournament >= 0) {
            $databaseTournament = $this->em->getRepository('AppBundle:Tournament')->find($tournament);
            if (is_null($databaseTournament)) {
                throw new EntityNotFoundException('Tournament (id:'.$tournament.') not found.');
            }
            else {
                $entry->setTournament($databaseTournament);
            }
        }
        else {
            throw new InvalidEntryArgumentException('Could not determine the Tournament argument.');
        }

        if ($team instanceof Team) {
            $entry->setTeam($team);
        }
        elseif (is_int($team) && $team >= 0) {
            $databaseTeam = $this->em->getRepository('AppBundle:Team')->find($team);
            if (is_null($databaseTeam)) {
                throw new EntityNotFoundException('Team (id:'.$team.') not found.');
            }
            else {
                $entry->setTeam($databaseTeam);
            }
        }
        else {
             throw new InvalidEntryArgumentException('Could not determine the Team argument.');
        }


        $entry->setEliminated($eliminated);
        return $entry;
    }
}

EntryController: EntryController:

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Entry;
use Doctrine\ORM\EntityNotFoundException;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\ConstraintViolationList;
use AppBundle\Factory;

class EntryController extends FOSRestController
{
    /**
     * @ApiDoc(
     *     resource=true,
     *     section="Entries",
     *     description="Creates a new entry.",
     *     statusCodes={
     *          201="Returned when created.",
     *          400="Returned when a violation is raised by validation.",
     *          404="Returned when a team or a tournament is not found."
     *     }
     * )
     *
     * @Rest\Post(
     *     path="/entries",
     *     name="app_entry_create"
     * )
     * @Rest\View(statusCode=201)
     * @Rest\RequestParam(
     *     name="tournamentId",
     *     requirements="\d+",
     *     nullable=false,
     *     description="The id of the tournament in which the team enters."
     * )
     * @Rest\RequestParam(
     *     name="teamId",
     *     requirements="\d+",
     *     nullable=false,
     *     description="The id of the team entering the tournament."
     * )
     *
     * @param $tournamentId
     * @param $teamId
     * @param ConstraintViolationList $violationList
     * @param Factory\EntryFactory $entryFactory
     * @return Entry|View
     * @throws EntityNotFoundException
     * @internal param $id
     * @internal param Entry $entry
     */
    public function createEntryAction($tournamentId, $teamId, ConstraintViolationList $violationList,
                                      Factory\EntryFactory $entryFactory)
    {
        if (count($violationList)) {
            return $this->view($violationList, Response::HTTP_BAD_REQUEST);
        }
        $entry = $entryFactory->createEntry($tournamentId,$teamId);
        $em->persist($entry);
        $em->flush();
        return $entry;
    }
}

edit: 编辑:

I must add that I've tried this and it doesn't work either: 我必须补充一点,我已经尝试过了,但是它也不起作用:

in the services.yml: services.yml中:

AppBundle\Factory\EntryFactory:
    public: true
    arguments: ['@doctrine.orm.entity_manager']

in the EntryFactory: EntryFactory中:

public function __construct(EntityManager $em)
{
    $this->em = $em;
}

edit 2: 编辑2:

I've also tried to disable everything new : still the same error 我也尝试禁用所有新功能:仍然是相同的错误

AppBundle\Factory\EntryFactory:
        autowire: false
        autoconfigure: false
        public: true
        arguments:
            $em: '@doctrine.orm.entity_manager'

Same with disabling the folder in the default config : 与在默认配置中禁用文件夹相同:

AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{Entity,Repository,Tests,Factory}'

You have write Service in your app/config/service.yml and add Factory : 您已在app/config/service.yml写入Service并添加Factory

services:
    AppBundle\:
        resource: '../../src/AppBundle/*'
        public: true
        exclude: '../../src/AppBundle/{Entity,Factory,Repository,Tests}'

    AppBundle\Factory\EntryFactory
        arguments: ['@doctrine.orm.entity_manager']

And We have pass EntityManager in __construct class EntryFactory look like: 并且我们在__constructEntryFactory传递了EntityManager ,如下所示:

class EntryFactory
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
................................................................
................................................................

An alternative to force autowiring Dependency Injection in Symfony 3.3 or later, without having to explicitly define the entity manager for each service. 在Symfony 3.3或更高版本中强制自动装配依赖关系注入的一种替代方法,而不必为每个服务显式定义实体管理器。 You can add an alias of the desired entity manager service . 您可以添加所需的实体管理器服务的别名

#app/config/services.yml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{Entity,Repository,Tests}'

    AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller'
        public: true
        tags: ['controller.service_arguments']

    Doctrine\ORM\EntityManagerInterface: '@doctrine.orm.entity_manager'

   #custom services below here
   #...

This will then allow Symfony to determine Doctrine\\ORM\\EntityManagerInterface as the service you want to inject. 然后,这将使Symfony将Doctrine\\ORM\\EntityManagerInterface确定为您要注入的服务。

use Doctrine\ORM\EntityManagerInterface;

class EntryFactory
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    //...
}

End result will be in your services configuration as: 最终结果将在您的服务配置中为:

return $this->services['AppBundle\Factory\EntryFactory'] = new \AppBundle\Factory\EntryFactory(${($_ = isset($this->services['doctrine.orm.default_entity_manager']) ? $this->services['doctrine.orm.default_entity_manager'] : $this->load('getDoctrine_Orm_DefaultEntityManagerService.php')) && false ?: '_'});

Note: Be sure to warmup your Symfony cache to ensure new service declarations are created. 注意:请确保预热您的Symfony缓存,以确保创建了新的服务声明。

 php composer.phar install 

or 要么

 php composer.phar install --no-scripts php bin/console --env=dev cache:clear --no-warmup` php bin/console --env=dev cache:warmup 

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

相关问题 Symfony 2 Doctrine 2 EntityManager配置 - Symfony 2 Doctrine 2 EntityManager config Doctrine和Symfony2无法合并新实体EntityManager#merge() - Doctrine and Symfony2 cannot merge new entity EntityManager#merge() Symfony 4:无法自动装配参数 $manager of ... 它引用接口“Doctrine\\Common\\Persistence\\ObjectManager” - Symfony 4 : Cannot autowire argument $manager of ... it references interface "Doctrine\Common\Persistence\ObjectManager" Symfony2学说,刷新entityManager跳过唯一性 - Symfony2 Doctrine, flush entityManager skip uniques Symfony 5.1 - 无法自动装配服务 - Symfony 5.1 - Cannot autowire service Symfony 无法自动装配服务 不存在此类服务 - Symfony cannot autowire service no such service exists Symfony 4:事件侦听器无法自动装配 UserInterface - Symfony 4: Event listener Cannot autowire UserInterface Symfony 3.4服务-Doctrine \\ ORM \\ EntityManager的实例,给定布尔值 - Symfony 3.4 Service - instance of Doctrine\ORM\EntityManager, boolean given 我该如何在Symfony2 / Doctrine中创建自定义EntityManager? - How exactly do I create a custom EntityManager in Symfony2/Doctrine? Symfony 4.4:无法自动连接服务“Symfony\Component\Validator\Context\ExecutionContextFactory” - Symfony 4.4: Cannot autowire service "Symfony\Component\Validator\Context\ExecutionContextFactory"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM