PHP-DI注解无法生效问题求助
Hey there! Let's walk through the common reasons why your @Inject annotation isn't taking effect and fix them step by step.
1. Make Sure Annotation Support is Enabled
PHP-DI doesn't enable annotation processing by default. You need to explicitly turn it on when building your container. Here's how:
use DI\ContainerBuilder; $containerBuilder = new ContainerBuilder(); // Enable annotation parsing $containerBuilder->useAnnotations(true); // Load your service definitions $containerBuilder->addDefinitions(__DIR__ . '/your-config-file.php'); $container = $containerBuilder->build();
Without this setting, PHP-DI will completely ignore any @Inject annotations in your classes.
2. Check the @Inject Annotation Namespace
You must import the correct Inject annotation class at the top of your ReportService file. If you skip this, PHP won't recognize the annotation as part of PHP-DI's system:
use DI\Annotation\Inject; // Don't forget this line! use CRM\Report\Service\ReportServiceContract; class ReportService implements ReportServiceContract { private $repository; /** * ReportService constructor. * @Inject("repositories.report_tasks") * * @param \CRM\Report\Repository\ReportTasksRepository $repository */ public function __construct($repository) { $this->repository = $repository; } // ... rest of your class }
3. Verify the "repositories.report_tasks" Service is Defined
The dependency you're trying to inject (repositories.report_tasks) must exist in your PHP-DI configuration. Double-check that you have a definition for it, like:
// In your config file return [ 'services.report'=> DI\autowire('\CRM\Report\Service\ReportService'), '\CRM\Report\Service\ReportServiceContract' => DI\get('services.report'), // Add this if it's missing! 'repositories.report_tasks' => DI\autowire('\CRM\Report\Repository\ReportTasksRepository'), ];
If this service isn't defined, PHP-DI won't know what to inject, which will either cause an error or leave your $repository property uninitialized.
4. Always Retrieve Instances from the Container
If you're manually creating the ReportService with new ReportService(), PHP-DI has no way to process the annotations. You must fetch the instance through the container:
// Correct way $reportService = $container->get(ReportServiceContract::class); // Or using the service alias $reportService = $container->get('services.report');
Only instances created by PHP-DI will have their dependencies injected via annotations.
内容的提问来源于stack exchange,提问作者user4671628

