Home > front end >  Symfony 6 fetching objects without a controller
Symfony 6 fetching objects without a controller

Time:11-01

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.

CodePudding user response:

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.

CodePudding user response:

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) {}
}
  • Related