Search code examples
symfonydoctrineentity

How to getRepository() for entity in subfolder with symfony 5.4?


Prior to Symfony 5.4 I used to reference my entities like this

public function findAction($archived = false)
{
    $em = $this->getDoctrine()->getManager();
    $analyses = $em->getRepository('App:Hazardlog\Analysis')->findAll();

I remember there was a new syntax for it ending with ::class a while back (possibly already in symfony 4) but I've been hanging on to this syntax because I have my entities organized into subfolders (a remnant from the old days when code in src was supposed to reside in a bunch of bundles...).

However, now all I get is a neat error saying

Class 'Analysis::class' does not exist

This is my directory structure

Entity
  Hazardlog
    Analysis
    Risk

Now, I have tried a number of ways to reference my entities with the ::class at the end, but none seem to work.

Can I simply not keep my directories in symfony 5.4 or is there a way of doing it that I just didn't find?

I've tried

$analyses = $em->getRepository('App:Hazardlog\Analysis::class')->findAll();

Also tried

$analyses = $em->getRepository('Hazardlog\Analysis::class')->findAll();

As well as

$analyses = $em->getRepository('Analysis::class')->findAll();

(last one was a longshot I know, but since there is only one Analysis entity in the app, and symfony is set on a new syntax, I thought maybe symfony would be smart enough to find it anyways 😂)

Any hints for me here?

------------------ UPDATE ---------------

From Cerad's comment I learned a few more ways that won't work

$analyses = $em->getRepository('App\Entity\Hazardlog\Analysis::class')->findAll();

$analyses = $em->getRepository('App\Entity\Hazardlog\Analysis\Analysis::class')->findAll();

And the way that actually works is

$analyses = $em->getRepository('App\Entity\Hazardlog\Analysis')->findAll();

Though I'm not sure if it's a bad idea to go with that, or if I should start referencing it with that "::class" appendage. What difference does it make?


Solution

  • Enclosing a bunch of characters in single quotes (') makes it a string. Therefore 'App\Entity\Hazardlog\Analysis::class' is a string. And that string is invalid as an argument to the getRepository method because it is not a valid classname. Therefore you need to use ->getRepository('App\Entity\Hazardlog\Analysis') instead - as that is the valid fully-qualified classname.

    Instead, using Analysis::class (notice, no quotes). Is a shortcut in php to create the valid fully-qualified classname for the class. So, you could use ->getRepository(Analysis::class) (again, no quotes) and php will convert the value. You will also notice in this case, that you must import the class - so up at the top of your class, you will have something like import App\Entity\Hazardlog\Analysis;. Without the import the ::class trick doesn't do its job.

    In the end, they are functionally the same. It is your preference which to use.