H
H
hiwibu2016-05-21 16:29:59
symfony
hiwibu, 2016-05-21 16:29:59

How to call a repository in symfony 2?

I do an example from docks. There is an entity and a repository, everything is generated through the console.
calling

$org = $this->getDoctrine()
            ->getRepository('MyOrgBundle:Organization')
            ->find(21);

writes
Fatal error: Call to undefined method My\OrgBundle\Entity\Organization::find()

In theory, he should look for OrganizationRepository, because. there method find() but for some reason takes Entity
upd
with User works
public function indexAction()
    {
        $org = $this->getDoctrine()
            ->getRepository(User::class)
            ->find(24);
        
        return array('name' => 'hdf');
    }

and like this - no
public function indexAction()
    {
        $org = $this->getDoctrine()
            ->getRepository(Organization::class)
            ->find(24);
        
        return array('name' => 'hdf');
    }

regenerated. checked the names. all the same

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-05-21
@hiwibu

1) Something tells me that it crashes on something like $product->find() and not on what you brought.
2) It's better to do this
3) It's even better to register repositories as services
4) Better yet, don't inherit from Doctrine repositories and use your own, which you can pass the entity manager to the constructor and do whatever you want there. Example (as it should be, it can be simplified in real projects)

class DoctrineOrganizationRepository implements OrganizationRepository 
{
    private $em;
    public function __construct(EntityManagerInterface $em) 
    {
          $this->em = $em;
    }

    public function getOrganization(int $id) : Organization
    {
           $organization = $this->em->find(Organization::class, $id);
           if (!$organization) {
                 throw new OrganizationNotFoundException();
           }
 
           return $organization;
    }
}

In essence, our application should not know too much about the doctrine. Well, it is even more convenient to register such services:
services:
     organization_repository:
         class: MyApp\Service\Doctrine\DoctrineOrganizationRepository
         autowire: true

5) Do not split the application into bundles. They are for reusing code. If you split the system into bundles with the thought "maybe I'll re-use later" - this is an example of premature optimization. You only need an AppBundle, and that's just for the little shortcuts.
There should be no dependencies between bundles. They may depend on libraries. but not from bundles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question