我是服务(以及drupal 8!)的新手,正在尝试弄清楚服务。我认为也许我只是在以过时的方式进行创建。我想要做的是使“ hello generator”成为服务,并使用以下命令在另一个控制器中调用它:
DBController.php
namespace Drupal\db\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\db\DbServices\HelloGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
class DBController extends ControllerBase
{
private $helloGenerator;
public function __construct(HelloGenerator $x) {
$this->helloGenerator = $x;
}
public function say($count) {
$hello = $this->helloGenerator->getHello($count);
return new Response($hello);
}
public static function create(ContainerInterface $container) {
$x = $container->get('db.hello_generator');
return new static ($x);
}
}
HellGenerator.php
命名空间Drupal \ db \ DbServices;
class HelloGenerator {
public function getHello($count) {
$foo = 4 + 4 + 4;
return $foo . ' ' . $count;
}
}
db.services.yml
services:
db.hello_generator:
class: Drupal\db\DbServices\HelloGenerator
db.db_says:
path: /db/says/{count}
defaults:
_controller: '\Drupal\db\Controller\DBController::say'
requirements:
_permission: 'access content'
您可以关注document。这是在控制器中调用服务的正确方法
—
MrD