logo

パレット - カラフルに🎨

Palette — ビジュアルページビルダー、デザインの専門知識は不要です。

ライブデモ パレットをダウンロード

Scroll

アクセスチェック + キャッシュ可能性

30/04/2020, by maria

ルートアクセスチェッカー、hook_entity_access()、およびAccessResultInterfaceオブジェクトを返す必要があるものはすべて、適切なキャッシュ可能性メタデータを追加する必要があります。

まだ読んでいない場合は、キャッシュタグキャッシュコンテキストmax-ageをお読みください。

アクセスチェックパラメータ

アクセスチェッカーは、さまざまなパラメーターを受け取ります。少なくともユーザーアカウント(AccountInterface)と、多くの場合エンティティです。次に、これらのパラメーターのプロパティに基づいて決定を行います。

そのパラメーターの少なくとも1つのプロパティの変更がアクセス結果を変更する場合は、$parameterへのキャッシュ可能な依存関係を追加する必要があります。

例:

$access_result = AccessResult::allowedIf($node->isPublished())
  // Access result depends on a property of the object that might change: it is a cacheable dependency.
  ->addCacheableDependency($node);

もう1つの一般的なケースは、アクセス結果が変更できないプロパティ(通常はID、UUID)に依存する場合です。たとえば、指定されたユーザーアカウントがエンティティの所有者である場合にアクセスを許可します:

$access_result = AccessResult::allowedIf($node->getOwnerId() === $account->id())
  // Access result depends on the node's owner, the owner might change.
  ->addCacheableDependency($node);

// Access result also depends on a user account, and the ID of the user account can never change. Hence we don't need to add $account as a cacheable dependency.

// But, if $account is the current user, and not some hardcoded user, we also need to make sure we vary this by the current user, so that we don't run this access check once and then reuse its result for all users.
if ($account->id() === \Drupal::currentUser()->id()) {
  $access_result->cachePerUser();
}