【问题标题】:New project using Symfony 4 with MongoDB / service not found未找到使用 Symfony 4 和 MongoDB / 服务的新项目
【发布时间】:2018-05-15 13:28:21
【问题描述】:

我正在尝试使用 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 服务器连接不起作用并且由于某种原因它没有被记录并且服务不会加载?

【问题讨论】:

标签: mongodb symfony symfony4


【解决方案1】:

你可以使用自动装配

use Doctrine\ODM\MongoDB\DocumentManager as DocumentManager;

public function createProduct(DocumentManager $dm)

【讨论】:

    【解决方案2】:

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

    class DefaultController extends Controller 
    

    【讨论】:

    • 有时这很容易 :) 现在我收到一条正确的错误消息,告诉我我的服务器连接有问题,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多