IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

Cannot autowire service "App\Controller\PropertyController"


Sujet :

Symfony PHP

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre très actif
    Homme Profil pro
    Consultant Marketing
    Inscrit en
    Mars 2016
    Messages
    293
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : Belgique

    Informations professionnelles :
    Activité : Consultant Marketing
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Mars 2016
    Messages : 293
    Par défaut Cannot autowire service "App\Controller\PropertyController"
    Bonsoir,

    J'ai un soucis je reçois ce message d'erreur, je pense que tout est bon dans mon code ?

    Avez vous une idée ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Cannot autowire service "App\Controller\PropertyController": argument "$em" of method "__construct()" references interface "Doctrine\Common\Persistence\ObjectManager" but no such service exists. Did you create a class that implements this interface?
    Mon source : PropertyController.php

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
     
    <?php
     
    namespace App\Controller;
     
    use App\Entity\Property;
    use App\Repository\PropertyRepository;
    use Doctrine\Common\Persistence\ObjectManager;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Routing\Annotation\Route;
     
    class PropertyController extends AbstractController
    {
        /**
         * @var PropertyRepository
         */
        private $repository;
        /**
         * @var ObjectManager
         */
        private $em;
     
        public function __construct(PropertyRepository $repository, ObjectManager $em)
        {
            $this->repository = $repository;
            $this->em = $em;
        }
     
        /**
         * @Route("/biens", name="property.index")
         * @return Response
         */
        public function index(): Response 
        {
            $property = $this->repository->findAllVisible();
            $property[0]->setSold(true);
            $this->em->flush();
            return $this->render('property/index.html.twig', [
                'current_menu' => 'properties'
            ]);
        }
     
    }
    Mon source : PropertyRepository.php

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
     
    <?php
     
    namespace App\Repository;
     
    use App\Entity\Property;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Doctrine\Persistence\ManagerRegistry;
     
    /**
     * @method Property|null find($id, $lockMode = null, $lockVersion = null)
     * @method Property|null findOneBy(array $criteria, array $orderBy = null)
     * @method Property[]    findAll()
     * @method Property[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
     */
    class PropertyRepository extends ServiceEntityRepository
    {
        public function __construct(ManagerRegistry $registry)
        {
            parent::__construct($registry, Property::class);
        }
     
        /**
         * @return Property[]
         */
        public function findAllVisible(): array
        {
            return $this->createQueryBuilder('p')
                ->where('p.sold = false')
                ->getQuery()
                ->getResult();
        }
        // /**
        //  * @return Property[] Returns an array of Property objects
        //  */
        /*
        public function findByExampleField($value)
        {
            return $this->createQueryBuilder('p')
                ->andWhere('p.exampleField = :val')
                ->setParameter('val', $value)
                ->orderBy('p.id', 'ASC')
                ->setMaxResults(10)
                ->getQuery()
                ->getResult()
            ;
        }
        */
     
        /*
        public function findOneBySomeField($value): ?Property
        {
            return $this->createQueryBuilder('p')
                ->andWhere('p.exampleField = :val')
                ->setParameter('val', $value)
                ->getQuery()
                ->getOneOrNullResult()
            ;
        }
        */
    }

  2. #2
    Membre Expert
    Avatar de Alexandre T
    Homme Profil pro
    Chef de projets AMO
    Inscrit en
    Mai 2002
    Messages
    1 213
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Chef de projets AMO
    Secteur : Transports

    Informations forums :
    Inscription : Mai 2002
    Messages : 1 213
    Par défaut
    Bonjour,

    L'ObjectManager peut être appelé, mais en théorie, il est plus prudent d'appeler une interface pour éviter ce genre d'écueil lors de l'injection de dépendance.

    Dans ton constructeur, je te recommande de remplacer ObjectManager par EntityManagerInterface. (Doctrine/ORM/EntityManagerInterface)

    Si cela ne résout pas ton souci, peux-tu remonter ton fichier services.yaml et ta version de Symfony ?
    Alexandre Tranchant
    Chef de projet AMO pour le Cerema.
    Retrouvez mes articles sur PHP et Symfony

  3. #3
    Membre très actif
    Homme Profil pro
    Consultant Marketing
    Inscrit en
    Mars 2016
    Messages
    293
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : Belgique

    Informations professionnelles :
    Activité : Consultant Marketing
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Mars 2016
    Messages : 293
    Par défaut
    Bonjour,

    Merci à vous sa fonctionne j'ai changer comme vous me l'avez indiquer :
    Pour ma version je suis avec la 4.4

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    public function __construct(PropertyRepository $repository, EntityManagerInterface $em)
        {
            $this->repository = $repository;
            $this->em = $em;
        }
    je pense que mon code est bon ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    <?php
     
    namespace App\Controller;
     
    use App\Entity\Property;
    use App\Repository\PropertyRepository;
    use Doctrine\Common\Persistence\ObjectManager;
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Routing\Annotation\Route;
     
    class PropertyController extends AbstractController
    {
        /**
         * @var PropertyRepository
         */
        private $repository;
        /**
         * @var ObjectManager
         */
        private $em;
     
        public function __construct(PropertyRepository $repository, EntityManagerInterface $em)
        {
            $this->repository = $repository;
            $this->em = $em;
        }
     
        /**
         * @Route("/biens", name="property.index")
         * @return Response
         */
        public function index(): Response 
        {
            $property = $this->repository->findAllVisible();
            $property[0]->setSold(true);
            $this->em->flush();
            return $this->render('property/index.html.twig', [
                'current_menu' => 'properties'
            ]);
        }
     
    }
    code source services.yaml

    Code yaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    # This file is the entry point to configure your own services.
    # Files in the packages/ subdirectory configure your dependencies.
     
    # Put parameters here that don't need to change on each machine where the app is deployed
    # https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
    parameters:
     
    services:
        # default configuration for services in *this* file
        _defaults:
            autowire: true      # Automatically injects dependencies in your services.
            autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
     
        # makes classes in src/ available to be used as services
        # this creates a service per class whose id is the fully-qualified class name
        App\:
            resource: '../src/*'
            exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
     
        # controllers are imported separately to make sure services can be injected
        # as action arguments even if you don't extend any base controller class
        App\Controller\:
            resource: '../src/Controller'
            tags: ['controller.service_arguments']
     
        # add more service definitions when explicit configuration is needed
        # please note that last definitions always *replace* previous ones

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Service windows - app.conf
    Par Aurélien19 dans le forum C#
    Réponses: 7
    Dernier message: 07/10/2008, 13h32
  2. Cannot find service endpoint
    Par maysam dans le forum Services Web
    Réponses: 0
    Dernier message: 29/08/2008, 15h53
  3. Réponses: 15
    Dernier message: 22/07/2008, 14h24
  4. [Framework] Utilisation des services dans un controller
    Par Ylias dans le forum Spring
    Réponses: 2
    Dernier message: 08/06/2008, 21h45

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo