【发布时间】:2014-09-17 13:54:12
【问题描述】:
我在 Symfony2 中有一个 Timesheet.php 类,我需要在这个类中使用例如:
$this->getDoctrine()->getRepository()->find();
$this->getDoctrine()->getManager()->remove();
我该怎么做?我尝试将类调用为服务,在构造函数中手动添加变量等但没有效果...
你有好的解决方案吗?
【问题讨论】:
我在 Symfony2 中有一个 Timesheet.php 类,我需要在这个类中使用例如:
$this->getDoctrine()->getRepository()->find();
$this->getDoctrine()->getManager()->remove();
我该怎么做?我尝试将类调用为服务,在构造函数中手动添加变量等但没有效果...
你有好的解决方案吗?
【问题讨论】:
这是因为$this->getDoctrine() 是Symfony\Bundle\FrameworkBundle\Controller 类的方法。当您检查此方法时,有$this->container->get('doctrine') 所以您需要在您的Timesheet 类中提供doctrine。为此,请将您的 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();
}
}
【讨论】: