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. 関連モジュール タイトル降順で並び替える
テーマ 8.3x Contribute themes drupal8-寄贈テーマの動向
拡張機能 8.3x Contribute modules drupal8-寄贈モジュールの動向
Viewsプログラミング 8.4x Views drupal8におけるViewsプログラミング
サイト情報 8.9.x api Drupal::request() メモ
チューニング 7.26 PHP DrupalはNginxで動く?
サイトの構築 8.9.x Webform drupalを使用した登録、一覧表示の方法について
PHP 8.9.x drush drush sql:cli < が機能しない場合の対処
アップデート 7.34 Distribution(Commerce Kickstart) drushでcommerce_kickstartのアップデートに失敗する
drush 7.54 Drush Drushでdrupalサイトをインストールする方法
サイトの構築 7.34 ECK Entityの使い方について
コンテンツの管理 8.4x Entity EntityをPropertyで探す(クエリする)方法
コンテンツの作成 8.4x PhpSpreadsheet Excelを読み書きする方法
表示 7.34 Views Infinite Scroll Facebookページのようにスクロールするとコンテンツが追加されるようなコントロール
フォーム 8.9.x api GET/POSTされた情報を得る方法
Gmian 8.8.x Gmail Gmail:外部メールサーバー経由のメール送信ができなくなった場合の対処方法
Google 7.38 robots.txt Google Search Console Teamから「CSS および JS ファイルに Googlebot がアクセスできません」
Initial 8.4x Subscriber hook_init() 〜 drupal_goto() を drupal8でやる方法
GoogleMaps 7.28 Javascript IE9でGoogle Map APIを利用した住所情報所得がうまくゆかない
サイト情報 8.4x JavaScript JavaScriptに変数を渡す方法
jQuery Revolution 7.50 jQuery Revolutionのリンクがスマホで機能しない

ページ