How to get the current user information in a Block plugin

Recently, while working on a project I had to build a block to show the user information of the currently logged-in user. Although it's a straight forward thing to do, the important thing to consider here is caching. Setting the cache max-age to 0 have performance impacts if the block has to be shown on all pages. So, the block has to leverage Drupal's Cache API to have a performant block with proper caching.

Caching the block

Since, the block needs to show the current logged in user information so the cache tags had to be set for user ID of the logged-in user with a context of user. But, for an anonymous user since there will be user ID so, the block will just return the parent cache context i.e ContextAwarePluginBase which is extended by BlockBase.


currentUser = $current_user;
    $this->userStorage = $user_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

  /**
   * Get the user info.
   */
  protected function getUser() {
    if ($this->currentUser->id() === 0) {
      return FALSE;
    }

    $user = $this->userStorage->load($this->currentUser->id());
    return $user;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build['content'] = [
      '#markup' => $this->getUser() ? $this->getUser()->label() : Link::createFromRoute($this->t('Log in'), 'user.login')->toString(),
    ];

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['user']);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    if ($user = $this->getUser()) {
      return Cache::mergeTags(parent::getCacheTags(), ['user', $user->id()]);
    }

    return parent::getCacheTags();
  }

}
malabyaFri, 08/07/2020 - 14:26Drupal development?>