Symfony2,在课堂上使用getDoctrine和em
我在Symfony2中有一个Timesheet.php类,在这个类中,我需要使用例如:Symfony2,在课堂上使用getDoctrine和em,symfony,doctrine,Symfony,Doctrine,我在Symfony2中有一个Timesheet.php类,在这个类中,我需要使用例如: $this->getDoctrine()->getRepository()->find(); $this->getDoctrine()->getManager()->remove(); 我该怎么做?我尝试将该类作为服务调用,在构造函数中手动添加变量,但没有效果 你有一个好的解决方案吗?这是因为$This->getDoctrine()是Symfony\Bundle\Fram
$this->getDoctrine()->getRepository()->find();
$this->getDoctrine()->getManager()->remove();
我该怎么做?我尝试将该类作为服务调用,在构造函数中手动添加变量,但没有效果
你有一个好的解决方案吗?这是因为
$This->getDoctrine()
是Symfony\Bundle\FrameworkBundle\Controller
类的方法。当您选中此方法时,会出现$this->container->get('doctrine')
,因此您需要的是在时间表
类中提供doctrine
。为此,请将时间表
类定义为服务:
your.service_id:
class: Acme\DemoBundle\Timesheet
arguments: [@doctrine]
然后您的时间表
课程:
use Doctrine\Bundle\DoctrineBundle\Registry;
class Timesheet
{
/**
* @var Registry
*/
private $doctrine;
/**
* @param Registry $doctrine Doctrine
*/
public function __construct(Registry $doctrine)
{
$this->doctrine = $doctrine;
}
public function yourMethod()
{
//this is what you want to achieve, right?
$this->doctrine->getManager()->remove();
$this->doctrine->getRepository()->find();
}
}
当然,除非时间表是从数据库加载的。这种事情应该避免,但你可以用:@Cerad为什么要避免这种事情?我很好奇,因为我也曾使用过这种方法。基本思想是条令2实体不需要知道数据库的细节。对象关系管理器(ORM)应该关注对象,而不是数据库表。这绝对是一种不同的应用程序设计方式。当然,使用globals通常是不受欢迎的。在这种特殊情况下,加载时间表对象时,它应该已经与它需要了解的任何对象具有所有关系。因此,不需要访问存储库。