Symfony 3.4调用getDoctrine()报错,容器为空求助
It sounds like your controller isn't properly accessing the service container, which is why $this->getDoctrine() is failing and triggering a 500 error. Let's walk through the most common fixes:
Ensure your controller is registered with the service container
Symfony relies on its service container to inject dependencies like Doctrine. If autowiring is enabled (default in Symfony 4+), confirm your controller lives in thesrc/Controller/directory and yourservices.yamlincludes this configuration:services: App\Controller\: resource: '../src/Controller/' tags: ['controller.service_arguments']If you're manually registering the controller, make sure it's set up to receive container injections.
Stop manually instantiating your controller
If you're creating the controller withnew YourController()anywhere in your code, the container won't be injected. Always let Symfony's routing system or service container handle instantiation for you.Avoid overriding the constructor without injecting the container
If your controller has a custom constructor, you need to either inject the container explicitly or (better yet) inject Doctrine directly:// Option 1: Inject EntityManager directly (recommended) use Doctrine\ORM\EntityManagerInterface; class YourController extends Controller { private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } public function returnObjectAction() { // Use the injected EntityManager instead of getDoctrine() $repository = $this->entityManager->getRepository(YourEntity::class); // ... rest of your code } } // Option 2: Inject container if you must use getDoctrine() use Symfony\Component\DependencyInjection\ContainerInterface; class YourController extends Controller { public function __construct(ContainerInterface $container) { $this->setContainer($container); } }Injecting specific dependencies (like EntityManager) is the modern Symfony best practice—it's more explicit and avoids tight coupling to the container.
Clear your Symfony cache
Cached service definitions can cause weird issues. Run these commands to reset the cache:php bin/console cache:clear php bin/console cache:clear --env=prod # If working in productionCheck your server logs for detailed errors
The 500 error is generic—look intovar/log/dev.log(orprod.logfor production) to see the actual exception stack trace. It might reveal a database connection issue, missing Doctrine configuration, or another underlying problem that's causing the container to fail.
内容的提问来源于stack exchange,提问作者hfvd

