hook_init() 〜 drupal_goto() を drupal8でやる方法

カテゴリ Initial コアバージョン 8.4x 関連モジュール Subscriber

modules/custom/your_module/your_module.services.yml

services:
  your_module.event_subscriber:
    class: Drupal\your_module\EventSubscriber\YourModuleSubscriber
    tags:
      - {name: event_subscriber}

modules/custom/your_module/src/EventSubscriber/Your_moduleSubscriber.php

<?php

namespace Drupal\your_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class YourModuleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    // 参考)一部の例外を除いて匿名ユーザーはloginページに飛ばす
    if (\Drupal::currentUser()->isAnonymous()) {
      if (!preg_match('!^(/user/|/sended-onetime-link-mail)!', $_SERVER['REQUEST_URI'])) {
        $path = \Drupal\Core\Url::fromUserInput('/user/login');
        $response = new RedirectResponse($path->toString());
        $response->send();
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

}

コメント

ユーザー actbrain の写真

動的キャッシュ再生成時に来させたい場合は 優先度 > 27 にする。

    $events[KernelEvents::REQUEST][] = ['checkForRedirection', 30];

何が何でも毎回来させたい場合は 優先度 > 200 にする。

    $events[KernelEvents::REQUEST][] = ['checkForRedirection', 280];

ページ

OTHER FAQ

Drupal開発・運用の疑問/質問の答えはここに

無料ユーザー登録すると質問できます。

カテゴリ降順で並び替える Core Ver. 関連モジュール タイトル
ダウンロード 6.x Views Bonus Pack Viewsで表示した内容をCSVダウンロード
チューニング 7.26 PHP DrupalはNginxで動く?
テーマ 8.7.x Bartikのtwigについて
テーマ 8.9.x patch パッチ 開発環境のファイル変更を本番環境にパッチでデプロイする方法(画像含まず)
テーマ 8.9.x スマホに向いたテーマについて
テーマ 7.23 hook ページや状況によってテーマを切り替える
テーマ 8.3x Contribute themes drupal8-寄贈テーマの動向
テーマ 7.34 スマホ、PCおよびアプリを同時に運用可能なおすすめのテーマはありますでしょうか?
テーマ 7.15 CSS Injector 簡単にCSSを追加したい
テーマ 8.4x hook_preprocess_html bodyタグにnode idやaliasのClassを追加する方法
テーマ 8.3x Theme drupal8 で パスに応じたページテンプレート名を利用する方法
テーマ 8.3x Core Twig開発用の設定
テーマ 7.56 field レンダリング配列内に「ラベル非表示」を指定する方法
テーマ 8.3x Block Cache Theme 管理ページから作成したカスタムブロックを非キャッシュ化する方法
テーマ 8.9.x Twig Twig で 月末日を算出する方法
ニュースレター 7.34 Simple news Simplenewsで追加顧客(リスト)だけにニュースレターを配信する方法
パフォーマンス 7.34 Server お金をかけないで冗長化するには
フォーム 7.38 Webform Webformモジュールをアップデートしたら「このフィールドを入力してください」
フォーム 8.6.x JavaScript 特定のformにJavaScriptを紐付ける方法
フォーム 7.43 Webform フォーム関数が実行されるタイミングについて

ページ