我在Symfony2中有一个Timesheet.php类,我需要在这个类中使用例如:
$this->getDoctrine()->getRepository()->find();
$this->getDoctrine()->getManager()->remove();
我该怎么做?我已经尝试将类作为服务调用,在构造函数中手动添加变量,但没有效果......
你有一个很好的解决方案吗?
答案 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();
}
}