skip to Main Content

In previous versions of symfony, you could fetch objects like this
`



public function someMethod()
{
    $method = $this->getDoctrine()->getRepository(Method::class)->findOneBy(array('id' => 1));


    return $method;
}

`
This was easy because it meant that you could easily make global variables in the twig.yaml file and have dynamic content all around your page.

Now in symfony as far as i know, an argument of ManagerRegistry has to be passed as a argument all the time. Am I being too close minded or is there a work around for this problem?

I tried extending classes and have it pass down that way but it gave me the same workaround errors.

2

Answers


  1. In a controller you can do either this :

    class MyController extends AbstractController {
        
        private EntityManagerInterface $em;
    
        public function __construct(EntityManagerInterface $em) {
             $this->em = $em;
        }
    }
    

    or

    class MyController extends AbstractController {
        { ... }
        public function someMethod(EntityManagerInterface $em) {
            $em->getRepository(SomeClass::class)
        }
    }
    

    I took a controller as an example but you can do this into your services. If you work with multiple entity manager, you can use the ManagerRegistry that extends AbstractManagerRegistry and use the method getManager($name)

    There is no real workaround for this as you always need to inject it. Depending on what you want to achieve, may be there is solution that can help.

    Login or Signup to reply.
  2. you can also directly inject the repository:

    public function someMethod(EntityRepository $repository) {
            $entities = $repository->findAll();
        }
    

    and of course you can inject it in the construct as well:

    class MyController extends AbstractController {
        
        private EntityRepository $repository;
    
        public function __construct(EntityRepository $repository) {
             $this->repository = $repository;
        }
    }
    

    if you are on php 8 you can write:

    class MyController extends AbstractController {
        
        public function __construct(private EntityRepository $repository) {}
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search