1

我正在尝试使用 MongoDB 创建一个新的 Symfony4 项目。

首先,我使用此文档创建了一个 Symfony4 项目: https ://symfony.com/doc/current/setup.html

然后我使用以下文档包含了 MongoDB:http: //symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html

我尝试尽可能地按照说明进行操作(例如,我不需要向 app/AppKernel.php 添加任何内容,但 MongoDB 会自动添加到 config/bundles.php)。

现在我认为一切都应该工作,但我的 Symfony 应用程序没有找到 MongoDB 服务:

You have requested a non-existent service "doctrine_mongodb". 
Did you mean one of these: "http_kernel", "request_stack", "router"?
in ServiceLocator.php (line 48)

控制器:

namespace App\Controller;

use App\Document\Chapter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends AbstractController {

    public function createAction() {
        $test = new Chapter();
        $test->setHeadline('Test');

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

        return new Response('Created product id '.$test->getId());
    }
}

但是,如果我在控制台上执行此操作:

php bin/console debug:container

我得到一个服务列表,其中包括:

doctrine_mongodb                                                                             Doctrine\Bundle\MongoDBBundle\ManagerRegistry
doctrine_mongodb.odm.default_connection                                                      Doctrine\MongoDB\Connection
doctrine_mongodb.odm.default_document_manager                                                Doctrine\ODM\MongoDB\DocumentManager
doctrine_mongodb.odm.document_manager                                                        alias for "doctrine_mongodb.odm.default_document_manager"

所以服务似乎在那里,但 Symfony 无法从我的应用程序中加载它。

知道我该如何解决这个问题吗?Mongo-DB 服务器连接是否可能不起作用并且由于某种原因它没有被记录并且服务不会加载?

4

2 回答 2

4

你可以使用自动装配

use Doctrine\ODM\MongoDB\DocumentManager as DocumentManager;

public function createProduct(DocumentManager $dm)

于 2018-10-11T08:34:21.017 回答
2

尝试从“Controller”而不是“AbstractController”扩展。

class DefaultController extends Controller 
于 2017-12-07T17:13:30.650 回答