在Symfony2示例中,我可以找到如何从Controller类访问mongodb:
$dm=$this->get('doctrine_mongodb')->getManager();
如何在仲裁类中做到这一点?
答案 0 :(得分:2)
您应该使用Dependency Injection将doctrine_mongodb
服务注入您的班级,就像这样。
像这样创建你的类:
use Doctrine\Common\Persistence\ObjectManager;
class MyClass
{
protected $documentManager;
// ObjectManager is the interface used only for type-hinting here
// DocumentManager or EntityManager are the actual implementations
public function __construct(ObjectManager $om)
{
// The property $documentManager is now set to the DocumentManager
$this->documentManager=$om;
}
public function findSomething()
{
// now do something with the DocumentManager
return $this->documentManager->getRepository('YourBundle:SomeDocument')->findBy(array(/* ... */));
// ...
}
然后将此类声明为服务:
# app/config/config.yml
services:
your_service_name:
class: Namespace\Your\SomeClass
arguments: ['@doctrine.odm.mongodb.document_manager']
为了从控制器访问您的类,它的服务名称是从容器中获取它(然后DocumentManager会自动注入到构造函数中)
// Vendor/YourBundle/Controller/SomeController.php
public function doWhatever()
{
$myClassService = $this->get('your_service_name');
$something = $myClassService->findSomething();
}