Symfony自动服务加载失败,“类不存在”

时间:2017-11-22 10:17:59

标签: php symfony dependency-injection

我正在使用Symfony的依赖注入组件(独立,不在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,用于自动加载的服务。

1 个答案:

答案 0 :(得分:3)

我的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();