Symfony2.3 在控制器中获取 EntityManager 的更好方法 [英] Symfony2.3 Better way to get EntityManager inside a Controller
问题描述
我正在使用 Symfony2.3
并且我目前正在使用 EntityManager,如 __construct()
I'm using Symfony2.3
and I currently using EntityManager as shown inside __construct()
使用 __construct() 中的 EntityManager 或在每个方法中使用哪个更好?如public indexAction()
Which its a better aproach using EntityManager from __construct() or using inside each method ? as shown in public indexAction()
/**
* QuazBar controller.
*
*/
class QuazBarController extends Controller
{
public function __construct()
{
$this->em = $GLOBALS['kernel']->getContainer()->get('doctrine')->getManager();
}
/**
* Lists all QuazBar entities.
*
*/
public function indexAction(Request $request)
{
$session = $request->getSession();
$pagina = $request->query->get('page', 1);
$em = $this->getDoctrine()->getManager();
}
推荐答案
如果你必须在你的构造函数中使用 EntityManager
,一个获得它的好方法是注入它给构造函数.
If you must have the EntityManager
available in your constructor, a good way to get it is injecting it to the constructor.
为此,您必须将您的控制器定义为服务.
# src/Acme/DemoBundle/Resources/config/services.yml
parameters:
# ...
acme.controller.quazbar.class: Acme\DemoBundle\Controller\QuazBarController
services:
acme.quazbar.controller:
class: "%acme.controller.quazbar.class%"
# inject doctrine to the constructor as an argument
arguments: [ @doctrine.orm.entity_manager ]
现在你要做的就是修改你的控制器:
Now all you have to do is modify your controller:
use Doctrine\ORM\EntityManager;
/**
* QuazBar controller.
*
*/
class QuazBarController extends Controller
{
public function __construct(EntityManager $em)
{
$this->em = $em;
}
// ...
}
如果您在构造函数中不需要 Entity Manager
,您可以简单地从控制器中的任何方法中使用依赖注入容器来获取它:
If you do not require the Entity Manager
in the constructor, you can simply get it using the Dependency Injection Container from any method in your controller:
$this->getDoctrine()->getManager();
或
$this->container->get('doctrine')->getManager();
控制器/setter 注入是一个不错的选择,因为您没有将控制器实现耦合到 DI 容器.
最终使用哪一种取决于您的需要.
At the end which one you use is up to your needs.
这篇关于Symfony2.3 在控制器中获取 EntityManager 的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!