简体   繁体   中英

Symfony2 Query placement

I have a simple question.

Should i place queries made with the entitymanager in the controllers or should i make separate classes and then call it with a service ?

example of query outside the controller :

protected $entityManager;
protected $securityContext;

public function __construct(EntityManager $entityManager, SecurityContext $securityContext) {
    $this->entityManager = $entityManager;
    $this->securityContext = $securityContext;
}

public function getTest() {
    $query = $this->entityManager->getRepository('PdbTestLoginBundle:PdbDomain')->find(972);
    if (!empty($query)) {
        return $query;
    } else {
        return false;
    }
}

Then i register a service like this :

`parameters: test.controller: Pdb\\TestLoginBundle\\Classes\\Test

services: test.defaultcontroller: class: "%test.controller%" arguments: entityManager: "@doctrine.orm.entity_manager" securityContext: "@security.context"

then i call it in the controller :

`$helper = $this->get('test.defaultcontroller'); var_dump($helper->getTest());

Is this the right way or should i directly make the query ???

You should put your query builders in Repository classes and tell the Entity class to use your Repository classes.

Repository classes have to extend Doctrine\\ORM\\EntityRepository class.

This means that $em->getRepository('Bundle:Entity') returns an object of your new Repository class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM