您可以通过“引用(注入)服务”来做到这一点。在您的情况下,您想注入 Request ,它是来自较窄范围的服务。
如果您正在使用转换器,您可能已经在使用自定义表单类型,并且正在您的表单类型BuildForm方法中实例化数据转换器,请参阅此处了解更多信息。
您想将 Request 对象注入自定义表单类型,然后可以将其作为构造函数参数传递给 Data Transformer。
为此,请修改services.yml
您的包中的文件,并将构造函数添加到自定义表单类型和自定义数据转换器,如下所示:
// src/Acme/HelloBundle/Resources/config/services.yml
parameters:
// ...
services:
acme.type.custom_type:
class: Acme\HelloBundle\Form\Type\CustomType
scope: request
arguments: ["@doctrine.odm.mongodb.document_manager", "@request"]
tags:
- { name: form.type, alias: custom_type }
像这样更新 CustomType 类:
<?php
// src/Acme/HelloBundle/Form/Type/CustomType.php
namespace Acme\HelloBundle\Form\Type;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ODM\MongoDB\DocumentManager;
use Acme\HelloBundle\Form\DataTransformer\CustomDataTransformer;
class CustomType extends AbstractType
{
private $request;
private $dm;
public function __construct(DocumentManager $dm, Request $request) {
$this->dm = $dm;
$this->request = $request;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Create a new Data Transformer that will be able to use the Request Object!
$transformer = new CustomDataTransformer($this->dm, $this->request);
$builder->addModelTransformer($transformer);
}
// ...
}
最后向转换器添加一个构造函数,类似于在表单类型中添加的构造函数:
<?php
// src/Acme/HelloBundle/Form/DataTransformer/CustomDataTransformer.php
namespace Acme\HelloBundle\Form\DataTransformer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\DataTransformerInterface;
use Doctrine\ODM\MongoDB\DocumentManager;
class CustomDataTransformer implements DataTransformerInterface
{
private $request;
private $dm;
public function __construct(DocumentManager $dm, Request $request) {
$this->dm = $dm;
$this->request = $request;
}
// ...
}
请注意,连同我已经注入 MongoDB DocumentManager 的请求,这是为了表明可以注入多个对象。