原文链接:https://www.drupal.org/node/2203931
依赖于Drupal服务或者自定义服务的表单应该通过依赖注入来访问该服务。
如一个表单(与Form API in Drupal 8 中的类似)使用'current_user'服务来获取当前用户的uid。假设模块名的modules/example,那么文件 /modules/example/lib/Drupal/example/Form/ExampleForm.php 内容:
<?php
/**
* @file
* Contains \Drupal\example\Form\ExampleForm.
*/
namespace Drupal\example\Form;
use Drupal\Core\Form\FormBase;
/**
* Implements an example form.
*/
class ExampleForm extends FormBase {
/**
* @var AccountInterface $account
*/
protected $account;
/**
* Class constructor.
*/
public function __construct(AccountInterface $account) {
$this->account = $account;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
// Instantiates this form class.
return new static(
// Load the service required to construct this class.
$container->get('current_user')
);
}
/**
* {@inheritdoc}.
*/
public function getFormID() {
return 'example_form';
}
/**
* {@inheritdoc}.
*/
public function buildForm(array $form, array &$form_state) {
// Get current user data.
$uid = $this->account->id();
// ...
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, array &$form_state) {
// ...
}
}
?>
create方法是一个返回ExampleFormObject新实例的工厂方法,加载一个或者多个服务。这些服务可以是任何核心服务,在core.services.yml 或者任何 *.services.yml 文件中定义。
ExampleForm::__construct 使用create方法中加载的服务并且保存在类的变量中。ExampleForm::create中加载服务的顺序需要与ExampleForm::__construct中的参数顺序一致。
create方法位于Drupal\Core\DependencyInjection\ContainerInjectionInterface中,允许控制器使用服务来初始化。Drupal\Core\Form\BaseForm已经实现了此接口。其他继承自Drupal\Core\Form\BaseForm的表单可以使用依赖注入,如ConfigFormBase 与 ConfirmFormBase。