0

在 Symfony2 示例中,我可以找到如何从 Controller 类访问 mongodb:

$dm=$this->get('doctrine_mongodb')->getManager();

如何在任意课程中做到这一点?

4

1 回答 1

2

您应该像这样使用依赖注入将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();
}
于 2013-10-25T21:16:09.053 回答