D8 - 我需要在我的街区使用许多服务,这个代码正确吗?
D8 - I need to use many services on my block, is this code right?
开发一个 Drupal 8 示例站点,我在一个模块中声明了块,我想用这个块做一些事情,比如检查路由并只在节点上显示这个块,还检查用户是否有查看这个块的权限,块的内容是我在模块的另一个地方定义的形式。
我不想以静态方式获得我需要的 classes/services,我想使用依赖注入来获得那些 类 因为分离代码在技术上更好并允许更好的测试。
现在"create"方法和块上的"constructor"方法是这样的:
<?php
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user'),
$container->get('form_builder'),
$container->get('current_route_match'),
$container->get('access_check.permission')
);
}
public function __construct(
array $configuration, $plugin_id,
$plugin_definition,
AccountProxyInterface $user,
FormBuilderInterface $formBuilder,
ResettableStackedRouteMatchInterface $route,
AccessInterface $access
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->user = $user;
$this->formBuilder = $formBuilder;
$this->route = $route;
$this->access = $access;
}
这是执行此操作的正确方法吗?也许我在块文件中做的太多了?我应该创建一个服务来将逻辑移动到另一个地方吗?可能我需要更多的东西,这意味着使用更多的服务,我的 "create" 和 "constructor" 方法的参数也在增加。这是正确的方法吗?谢谢
当您必须在一个 class 中注入许多服务时,无论是控制器还是块,它通常表明 class 设计不佳,因为您(可能)尝试了很多一件事情 class.
但是,我见过很多控制器在它们的构造函数中注入多个服务,所以无论如何这似乎并不是一种不寻常的做法。 "Every rule has an exception".
最后,我认为这是一个平衡的问题,建立一个class负责做一件合乎逻辑的事情,它的依赖也是一样的。
开发一个 Drupal 8 示例站点,我在一个模块中声明了块,我想用这个块做一些事情,比如检查路由并只在节点上显示这个块,还检查用户是否有查看这个块的权限,块的内容是我在模块的另一个地方定义的形式。
我不想以静态方式获得我需要的 classes/services,我想使用依赖注入来获得那些 类 因为分离代码在技术上更好并允许更好的测试。
现在"create"方法和块上的"constructor"方法是这样的:
<?php
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user'),
$container->get('form_builder'),
$container->get('current_route_match'),
$container->get('access_check.permission')
);
}
public function __construct(
array $configuration, $plugin_id,
$plugin_definition,
AccountProxyInterface $user,
FormBuilderInterface $formBuilder,
ResettableStackedRouteMatchInterface $route,
AccessInterface $access
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->user = $user;
$this->formBuilder = $formBuilder;
$this->route = $route;
$this->access = $access;
}
这是执行此操作的正确方法吗?也许我在块文件中做的太多了?我应该创建一个服务来将逻辑移动到另一个地方吗?可能我需要更多的东西,这意味着使用更多的服务,我的 "create" 和 "constructor" 方法的参数也在增加。这是正确的方法吗?谢谢
当您必须在一个 class 中注入许多服务时,无论是控制器还是块,它通常表明 class 设计不佳,因为您(可能)尝试了很多一件事情 class.
但是,我见过很多控制器在它们的构造函数中注入多个服务,所以无论如何这似乎并不是一种不寻常的做法。 "Every rule has an exception".
最后,我认为这是一个平衡的问题,建立一个class负责做一件合乎逻辑的事情,它的依赖也是一样的。