【问题标题】:Symfony 4 autowiring in Entity not working实体中的 Symfony 4 自动装配不起作用
【发布时间】:2019-01-18 18:14:39
【问题描述】:

我正在尝试在我的用户实体 Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface 中自动装配 并收到错误 App\Entity\User::__construct() 的参数太少。

public function __construct(UserPasswordEncoderInterface $encoder)
{
    $this->packages = new ArrayCollection();
    $this->passwordEncoder = $encoder;
}

在我的 services.yaml 中

services:
# default configuration for services in *this* file
_defaults:
    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
    public: false       # Allows optimizing the container by removing unused services; this also means
                        # fetching services directly from the container via $container->get() won't work.
                        # The best practice is to be explicit about your dependencies anyway.

# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

【问题讨论】:

  • 您看到 services.yaml 的“排除:...实体...”部分了吗?这特别说明不要在实体目录下自动装配任何东西。教义实体不是服务。对于大多数实际目的,您不能向其中注入东西。

标签: symfony entity autowired symfony4


【解决方案1】:

如评论中所述,实体不被视为服务,因此不能使用自动装配。

实体应该用于简单的数据操作。如果您需要访问其他 Symfony 组件,您的选择之一是创建一个管理器类来处理额外的工作或依赖事件侦听器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多