只需将您的订户视为服务即可。
Yml配置。你可以多余 autowire:true 如果你有自动连接的所有课程:
autowire:true
services: My\Form\Type: autowire: true tags: - { name: form.type } My\Form\Listener\MyNewListener: autowire: true
表格类:
... class MyForm extends AbstractType { /** * @var MyNewListener */ private $listener; /** * @param MyNewListener $listener */ public function __construct(MyNewListener $listener) { $this->listener = $listener; } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { ... $builder->addEventSubscriber($this->listener); } }
您可以将表单定义为容器中的服务,就像他在评论中提到的Cerad一样。
由于您使用的是Symfony 3,因此您可以选择配置服务 autowire: true ,或手动声明您的参数。然后在FormType中,您可以将这些类属性传递给Subscriber类。将表单定义为服务时,请务必使用标记 form.type 。这是下面的示例代码。
autowire: true
form.type
Services.yml
services: your.form.type: class: EventsBundle\Form\MarketerType autowire: true # this is not needed if using arguments arguments: [ '@doctrine.orm.entity_manager' ] # this is not needed if using autowire tags: - { name: form.type }
FormType.php
<?php namespace EventsBundle\Form; use Doctrine\ORM\EntityManager; use Symfony\Component\Form\AbstractType; ... class FormType extends AbstractType { /** @var EntityManager */ private $em; public function __construct(EntityManager $em) { $this->em = $em; } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { ... $builder->addEventSubscriber(new YourNewListener($this->em)); } ...
然后,为了安全起见,您需要清除应用程序缓存。我希望这有帮助!