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.昇順で並び替える 関連モジュール タイトル
コンテンツの作成 7.34 CCK ノード入力フォームへパラメータを渡す
CSV Download 7.34 Views Excel Export Drupal7:Viewsで表示した内容をCSVダウンロード
Calendar 7.34 Calendar CalendarモジュールとGoogleカレンダーを同期するには
ニュースレター 7.34 Simple news Simplenewsで追加顧客(リスト)だけにニュースレターを配信する方法
Commerce 7.34 Commerce kickstart, Commerce file Commerceモジュール利用時のダウンロード製品登録方法
アップデート 7.34 Distribution(Commerce Kickstart) drushでcommerce_kickstartのアップデートに失敗する
テーマ 7.34 スマホ、PCおよびアプリを同時に運用可能なおすすめのテーマはありますでしょうか?
コンテンツの作成 7.34 ajax 標準のajaxフォーム(複数値:値の数=無制限)の制御l方法
表示 7.34 Views Infinite Scroll Facebookページのようにスクロールするとコンテンツが追加されるようなコントロール
JavaScript 7.34 PHP PHPからJavaScriptに変数値を渡したい
token 7.34 token オリジナルモジュールからtokenを提供する方法を教えて下さい。
コンテンツの作成 7.34 Entityreference prepopulate 新規ノード作成時のリファレンス方法
Drupal Commerce 7.34 Commerce profile Drupal Commerceの請求情報、配送情報の住所を日本的(郵便番号、都道府県、市区町村、住所、、、)
フォーム 7.34 Webform 動的なフォーム(webform)
Messages 7.34 Disable messages 標準(コア)が表示する特定のメッセージ非表示にしたい
サイトの構築 7.34 ECK Entityの使い方について
アップデート 7.34 Core 簡単にCoreのセキュリティアップデートがしたい
サイトの構築 7.31 Views ブロックViewsの絞り込みが表示されない
コンテンツの作成 7.31 CKEditor CKEditorの新規生成ダイアログ内の初期値の変更
アップデート 7.28 Views Pagerが表示されなくなった

ページ