Skip to content

Instantly share code, notes, and snippets.

@joshirohit100
Created March 10, 2017 10:24
Show Gist options
  • Save joshirohit100/d81991607013f77541daac72418d607e to your computer and use it in GitHub Desktop.
Save joshirohit100/d81991607013f77541daac72418d607e to your computer and use it in GitHub Desktop.
Custom cache context sample
<?php
namespace Drupal\rohit\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a block to display 'Site branding' elements.
*
* @Block(
* id = "user_favorite_color_block",
* admin_label = @Translation("User favorite color")
* )
*/
class UserFavoriteColorBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$build = array();
$current_user_id = \Drupal::currentUser()->id();
// Load user object.
$user = User::load($current_user_id);
$favorite_color = $user->get('field_favorite_color')->getValue()[0]['value'];
$build['rohit'] = array(
'#markup' => 'User favorite color is ' . $favorite_color,
);
return $build;
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
return Cache::mergeContexts(
parent::getCacheContexts(),
['user_favorite_color']
);
}
}
<?php
namespace Drupal\rohit\CacheContext;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;
class UserFavoriteColorCacheContext implements CacheContextInterface {
/**
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
public function __construct(AccountProxyInterface $current_user) {
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function getLabel() {
return t('User favorite color cache context');
}
/**
* {@inheritdoc}
*/
public function getContext() {
$current_user_id = $this->currentUser->getAccount()->id();
// Load user object.
$user = User::load($current_user_id);
$favorite_color = $user->get('field_favorite_color')->getValue()[0]['value'];
return $favorite_color;
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata() {
return new CacheableMetadata();
}
}
services:
cache_context.user_favorite_color:
class: Drupal\rohit\CacheContext\UserFavoriteColorCacheContext
arguments: ['@current_user']
tags:
- { name: cache.context }
cache_context.my_cache_context:
class: Drupal\rohit\CacheContext\MyCacheContextClass
arguments: []
tags:
- { name: cache_context }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment