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.22 Realname ユーザーIDではなくニックネーム等を表示したい
ユーザ 7.44 Quickbar 会員の種別(役割)別にメニューを設けたい
SSH 7.50 ProxyCommand SSH IP制限を1コマンドで通過する
Proxy 7.59 Proxy Apache settings.php リバースプロキシ(Apache)+バックグランドWeb(Drupal 7 )でログインセッションを維持する方法
サイトの構築 7.19 Plesk Pleskでdrupal7(プライベートファイルシステム)を使う場合の注意点
コンテンツの作成 8.4x PhpSpreadsheet Excelを読み書きする方法
PHP 8.9.x PHP YamlをPHP配列にする方法
Database 7.34 PHP データベースクエリ(SELECT)時のSQL関数
JavaScript 8.5.x PHP Commerce決済モジュール設定をJavaScriptにデータに渡す方法
PHP 7.22 PHP ノードに付いたコメントを好きな場所に表示する
コンテンツの作成 7.26 PHP ノード内の一部(フィールド)を変更する
PHP 8.3x PHP drupa8でhook_init()する方法
アップデート 8.9.x PHP CentosでPHPのバージョンアップ(例:5.3->5.6)を行う方法
ユーザ 7.23 PHP user_load_multiple()の復帰値
ユーザの管理 7.27 PHP 新規ユーザーの追加ができない
コンテンツの管理 7.16 PHP 好きなところにノードを埋め込みたい
JavaScript 7.34 PHP PHPからJavaScriptに変数値を渡したい
チューニング 7.26 PHP DrupalはNginxで動く?
PHP-FPM 8.9.x PHP PHP-FPM 環境で .htaccess に php_value を 書いてもダメ
ユーザの管理 7.50 Paypal continued billing drupal7のPaypal継続課金モジュールについて

ページ