Symfony 4中如何通过依赖注入获取Doctrine DocumentManager?
Hey there, let's break down your two related issues one by one—getting the DocumentManager injected into your services, and that confusing reserved class name error.
1. Injecting DocumentManager into Services (Instead of Just Controllers)
The reason you can grab it in controllers but not services is simple: Symfony auto-registers Doctrine's EntityManager as a service out of the box, but it doesn't do the same for MongoDB's DocumentManager. You don't need to create a new service from scratch though—just alias the existing service that Doctrine MongoDB ODM already sets up.
Add this to your services.yaml:
services: # Alias the default DocumentManager to its full class for autowiring Doctrine\ODM\MongoDB\DocumentManager: alias: 'doctrine_mongodb.odm.document_manager' public: true # Only needed if you're using an older Symfony 4 version, but safe to add just in case # If you have multiple MongoDB connections, target the specific one like this: # Doctrine\ODM\MongoDB\DocumentManager $secondaryDocManager: # alias: 'doctrine_mongodb.odm.secondary_document_manager'
Now you can inject it directly into your service's constructor, just like you would with EntityManager:
use Doctrine\ODM\MongoDB\DocumentManager; class YourCustomService { private $docManager; public function __construct(DocumentManager $docManager) { $this->docManager = $docManager; } // Your service logic here }
Make sure you have autowire: true enabled in your _defaults section of services.yaml—that's what lets Symfony automatically match the class type to the service alias.
2. Fixing the "Cannot use 'Bool' as class name as it is reserved" Error
This error has nothing to do with DocumentManager registration—it's a PHP reserved keyword issue. PHP treats bool (and yes, even Bool, since it's case-insensitive) as a reserved type name, so you can't use it for a class name.
Check these places in your codebase:
- Any custom PHP classes you've created named
Bool.phpor with the class nameBool usestatements that import a class namedBoolfrom any namespace- Even accidental typos where you might have named a class
Boolinstead of something likeBoolean
Rename that class to something valid—like BooleanType, BoolValue, or CustomBool—and the compile error will disappear immediately.
Quick Pre-Check
Just to be thorough, confirm you've got the Doctrine MongoDB ODM bundle properly installed and enabled:
- Run
composer require doctrine/mongodb-odm-bundleif you haven't already - Verify
Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle::class => ['all' => true]is present inconfig/bundles.php
内容的提问来源于stack exchange,提问作者Attila the Hun

