Symfony2,在课堂上使用getDoctrine和em

时间:2014-09-17 13:54:13

标签: symfony doctrine

我在Symfony2中有一个Timesheet.php类,我需要在这个类中使用例如:

$this->getDoctrine()->getRepository()->find();
$this->getDoctrine()->getManager()->remove();

我该怎么做?我已经尝试将类作为服务调用,在构造函数中手动添加变量,但没有效果......

你有一个很好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

这是因为$this->getDoctrine()Symfony\Bundle\FrameworkBundle\Controller类的方法。当您检查此方法时,$this->container->get('doctrine')就是doctrine类所需的Timesheet。为此,请将您的Timesheet课程定义为服务:

your.service_id:
    class: Acme\DemoBundle\Timesheet
    arguments: [@doctrine]

然后是你的Timesheet课程:

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();
    }
}