简体   繁体   English

Symfony 4:无法自动装配参数 $manager of ... 它引用接口“Doctrine\\Common\\Persistence\\ObjectManager”

[英]Symfony 4 : Cannot autowire argument $manager of ... it references interface "Doctrine\Common\Persistence\ObjectManager"

when i submit my form i got this error :当我提交表单时出现此错误:

Cannot autowire argument $manager of "App\\Controller\\AdController::create()": it references interface "Doctrine\\Common\\Persistence\\ObjectManager" but no such service exists.无法自动装配“App\\Controller\\AdController::create()”的参数 $manager:它引用接口“Doctrine\\Common\\Persistence\\ObjectManager”,但不存在这样的服务。 You should maybe alias this interface to the existing "doctrine.orm.default_entity_manager" service.您可能应该将此接口别名为现有的“doctrine.orm.default_entity_manager”服务。

This is in function create in AdController.php:这是在 AdController.php 中的函数 create 中:

<?php

namespace App\Controller;

use App\Entity\Ad;
use App\Form\AdType;
use App\Repository\AdRepository;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class AdController extends AbstractController
{
    /**
     * @Route("/ads", name="ads_index")
     */
    public function index(AdRepository  $repo)
    {
        $ads = $repo->findAll();

        return $this->render('ad/index.html.twig', [
            'ads' => $ads,
        ]);
    }

    /**
     * @Route("/ads/new", name="ads_create")
     * 
     * @return Response
     */

    public function create(Request $request, ObjectManager $manager){
        $ad = new Ad();



        $form = $this->createForm(AdType::class, $ad);

        $form->handleRequest($request);//symfony va faire le lien entre les donne des champs fu formulaire et la variable $ad

        if($form->isSubmitted() && $form->isValid() ){
            $manager->persist($ad);
            $manager->flush();
        }

        return $this->render("ad/new.html.twig", [
            'form' => $form->createView()
        ]);
    }

    /**  
     * @Route("/ads/{slug}", name="ads_show")
     * @return Response
     */
    public function show(Ad $ad){
        return $this->render('ad/show.html.twig', [
            'ad' => $ad
        ]);
    }
}

and this is my AdType.php :这是我的 AdType.php :

<?php

namespace App\Form;

use App\Entity\Ad;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;

class AdType extends AbstractType

{

/**
 * @param string $label
 * @param string $placeholder
 * @return array
 */
private function getConfiguration($label, $placeholder){
    return [
        'label' => $label,
        'attr' => [
            'placeholder' => $placeholder
        ]
    ];
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title', TextType::class, $this->getConfiguration("titre", "tapez un super titre pour votre annonce"))
        ->add('slug', TextType::class, $this->getConfiguration("Adresse web", "tapez l'adresse web (automatique)"))
        ->add('coverImage', UrlType::class, $this->getConfiguration("Url de l'image principal", "Donnez l'adresse d'une image qui donne vraiment envie"))
        ->add('introduction', TextType::class, $this->getConfiguration("introduction", "donnez une description global de l'annonce"))
        ->add('content', TextareaType::class, $this->getConfiguration("Description detaille", "tapez une description qui donne vraiment envie de venir chez vous !"))
        ->add('price', MoneyType::class, $this->getConfiguration("Prix par nuit", "indiquez le prix que voulez pour une nuit"))
        ->add('rooms', IntegerType::class, $this->getConfiguration("Nombre de chambre", "le nom de chambres disponibles"))
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => Ad::class,
    ]);
}

} }

Why i get this error when i submit my form and how can i solve this problem为什么在提交表单时出现此错误以及如何解决此问题

Thank you in advance先感谢您

You should avoid using directly the service.您应该避免直接使用该服务。 Always use the contract instead.始终使用合约代替。 It is available for every services它适用于所有服务

So instead of using ObjectManager directly, use EntityManagerInterface所以不要直接使用ObjectManager ,而是使用EntityManagerInterface

The error actually says you should alias that class to an existing service.该错误实际上是说您应该将该类别名为现有服务。 That happens when Symfony does not know which implementation of interface you are going to use.当 Symfony 不知道您将使用哪种接口实现时,就会发生这种情况。

Try something like this:尝试这样的事情:

Doctrine\Common\Persistence\ObjectManager: '@doctrine.orm.default_entity_manager'

Add it in services.yml and try.将其添加到 services.yml 中并尝试。

docs: https://symfony.com/doc/current/service_container/autowiring.html#using-aliases-to-enable-autowiring文档: https : //symfony.com/doc/current/service_container/autowiring.html#using-aliases-to-enable-autowiring

use ManagerRegistry service instead of ObjectManager使用ManagerRegistry服务代替ObjectManager

/**
 * @Route("/ads/new", name="ads_create")
 * 
 * @return Response
 */

public function create(Request $request, ManagerRegistry $managerRegistry){
    $ad = new Ad();

    $form = $this->createForm(AdType::class, $ad);

    $form->handleRequest($request);//symfony va faire le lien entre les donne des champs fu formulaire et la variable $ad

    if($form->isSubmitted() && $form->isValid() ){
        $em = $managerRegistry->getManager();
        $em->persist($ad);
        $em->flush();
    }

    return $this->render("ad/new.html.twig", [
        'form' => $form->createView()
    ]);
}

try with this:试试这个:

use Doctrine\ORM\EntityManagerInterface;

class Someclass {
protected $em;

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

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

}

You must change this use:您必须更改此用途:

use Doctrine\Common\Persistence\ObjectManager;

to this use:用于此用途:

use Doctrine\Persistence\ObjectManager;

Try changing this尝试改变这个

$manager->persist($ad);
$manager->flush();

To this对此

$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();

尝试使用EntityManagerInterface而不是ObjectManager

You must change this:你必须改变这一点:

$manager->persist($ad);
$manager->flush();

To this:对此:

$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();

暂无
暂无

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

相关问题 类 Doctrine\Common\Persistence\ObjectManager 不存在 - Class Doctrine\Common\Persistence\ObjectManager does not exist Symfony2表单事件侦听器和数据转换器错误无法实例化接口Doctrine \\…\\ ObjectManager - Symfony2 Form Events Listener and Data Transformer Error Cannot instantiate interface Doctrine\…\ObjectManager 无法在Symfony中使用自动装配获取Doctrine EntityManager - Cannot fetch the Doctrine EntityManager with autowire in Symfony 无法自动装配“App\Controller\HomeController”参数 $:它引用 class“Symfony\Component\Form\SubmitButton”但不存在此类服务 - Cannot autowire argument $of "App\Controller\HomeController": it references class "Symfony\Component\Form\SubmitButton" but no such service exists Symfony:无法自动装配“Controller:method()”的参数 $injectedVar:它引用 class“App\Entity\Entity”,但不存在此类服务 - Symfony: Cannot autowire argument $injectedVar of "Controller:method()": it references class "App\Entity\Entity" but no such service exists 传递给 DoctrineDataCollector::__construct() 的参数 1 必须是 Doctrine\Common\Persistence\ManagerRegistry 的一个实例 - Argument 1 passed to DoctrineDataCollector::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry 无法自动装配服务:参数引用 class 但不存在此类服务 - Cannot autowire service: Argument references class but no such service exists symfony 中的自动装配 Predis 接口 - autowire Predis Interface in symfony Symfony 5 无法为动态数据库连接自动装配参数 $Driver - Symfony 5 Cannot autowire argument $Driver for a dynamic database connection 更新 Doctrine 后,Symfony 中的“ObjectManager 和 EntityManagerInterface 之间的兼容性”是什么? - what's the " compatibility between ObjectManager and EntityManagerInterface " in Symfony after update Doctrine?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM