gpt4 book ai didi

php - 无法在 Symfony 中使用 Autowiring 获取 Doctrine EntityManager

转载 作者:行者123 更新时间:2023-12-03 19:38:44 25 4
gpt4 key购买 nike

好吧,我要疯了,Symfony (3.3) Autowiring 有一些我无法理解的东西。我读过这些资源: http://symfony.com/doc/current/service_container.html http://symfony.com/doc/current/service_container/3.3-di-changes.html以及其他我无法发布的内容,因为我需要 10 个声望。我也读过很多文章/stackoverflow 帖子,但没有运气。

我已尝试设置我的服务,它几乎可以正常工作,只是 EntityManager 为空,所以我无法对其调用 ->getRepository()。错误发生在我工厂这样的线上:

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

"Call to a member function getRepository() on null"

它似乎正确地找到了服务,但从未在工厂中注入(inject) EntityManager。我试图在 services.yml 中明确配置一些东西,但我从来没有设法让它工作。

从昨天开始我就想弄明白了,但我真的很困惑。你可以帮帮我吗 ?先感谢您 ! :)

这是我的文件:

服务.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']

入口工厂:

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

入口 Controller :

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

编辑:

我必须补充一点,我已经尝试过了,但它也不起作用:

services.yml中:

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

EntryFactory 中:

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

编辑 2:

我也试过禁用所有新的:仍然是同样的错误

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

与禁用默认配置中的文件夹相同:

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

最佳答案

强制的替代方法 autowiring Dependency Injection in Symfony 3.3或更高版本,而不必为每个服务显式定义实体管理器。您可以添加 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
#...

这将允许 Symfony 将 Doctrine\ORM\EntityManagerInterface 确定为您要注入(inject)的服务。

use Doctrine\ORM\EntityManagerInterface;

class EntryFactory
{
private $em;

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

//...
}

最终结果将在您的服务配置中为:

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 servicedeclarations are created.

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

关于php - 无法在 Symfony 中使用 Autowiring 获取 Doctrine EntityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45399274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com