我正在尝试使用Symfony的Dependency Injection组件(独立的,不在Symfony应用程序中)v3.3.13版加载新的自动服务.
如果我手动定义服务,则该类将正确加载:
# services.yml
myasset:
class: Mysite\Asset\Asset
# in a PHP file
$container->get('myasset'); # works
如果设置自动加载,它将失败并显示错误消息:
ReflectionException:类在第1070行的/var/www/vendor/symfony/dependency-injection/ContainerBuilder.php中不存在
# services.yml
_defaults:
autowire: true
autoconfigure: true
public: false
Bloggi\:
resource: '../src/*'
public: true
# in a PHP file
$container->get(Mysite\Asset\Asset::class);
失败的原因是因为找到了类并创建了服务定义,但是对于自动加载的服务,定义上的class属性为null.
解决方法:
我的DIC配置如下所示:
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$loader->load(__DIR__ . '/../config/services.yml');
缺少的行是$container-> compile();
工作定义
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$loader->load(__DIR__ . '/../config/services.yml');
$container->compile();
标签:symfony,dependency-injection,php
来源: https://codeday.me/bug/20191110/2014806.html