James May
James May

Reputation: 1537

Organize the models in Symfony 3

I just read the official Symfony 3 docs and point when I need to retrieve objects from database I should use something like this:

$repository = $em->getRepository('AppBundle:Product');

Here Product is just an entity class with no parent, so Doctrine work with it through annotations. But I'm not sure it's a good idea to hardcode the model name in quotes. What if later I conclude to name the model Good, should I search through the whole project and replace Product on Good. I Laravel for example, each model extends the base model class so I could write : Product::model()->find('nevermind') . Is there any such option in Symfony 3.3?

Upvotes: 5

Views: 709

Answers (3)

COil
COil

Reputation: 7606

You can declare the repository as a service like this:

services:
    app.product_repo:
        class: AppBundle\Entity\ProductRepository
        factory: ['@doctrine.orm.default_entity_manager', getRepository]
        arguments:
            - AppBundle\Entity\Product

Then in your controller:

$repository = $em->get('app.product_repo');

Well at least it works with PHPStorm and its Symfony plugin. Having auto-complete for services is really a must.

Upvotes: 1

odan
odan

Reputation: 4952

The $em->getRepository('...') returns a mixed datatype (depends on the first parameter). Even you write $repository = $em->getRepository(Product::class); the IDE cannot resolve the real datatype. I suggest this method (pseudo code):

/**
 * Get product repo
 *
 * @return ProductRepository
 */
 public function getProductRepository() 
 {
     return $this->getEntityManager()->getRepository(Product::class);
 }

 /**
  * @return \Doctrine\ORM\EntityManager
  */
 public function getEntityManager(): EntityManager
 {
     return $this->getDoctrine()->getManager();
 }

Upvotes: 1

Lukas
Lukas

Reputation: 56

I'm not shure if it is a solution for your problem, but you can write:

$repository = $em->getRepository(Product::class);

Upvotes: 4

Related Questions