Drupal 10 如何实现 Drupal 7 中 hook_init() 的功能?
发布于
Drupal 7 中的 hook_init() 可以用于在页面初始化时执行代码,Drupal 10 没有这个 hook 了,请问 Drupal 10 要在页面初始化时执行代码该怎么做?
1 个回答
Drupal 8 开始内核已经移除 hook_init()
, 相同的功能可以通过 Event Subscriber 监听和响应 KernelEvents::REQUEST
事件来实现。
首先需要在模块根目录创建 mymodule.services.yml
文件,并添加如下内容。
注意:mymodule
都需改为你的模块机器名。
services:
mymodule.event_subscriber:
class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
tags:
- {name: event_subscriber}
创建 modules/src/EventSubscriber/MymoduleSubscriber.php
文件(文件名与上方服务声明中的 class 一致),参考下方代码实现所需要的逻辑。
namespace Drupal\mymodule\EventSubscriber;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MymoduleSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = ['requestHandler'];
return $events;
}
public function requestHandler(RequestEvent $event) {
if ($event->getRequest()->query->get('redirect')) {
$event->setResponse(new RedirectResponse('http://example.com/'));
}
}
}