Drupal 8 Block with Dependency injection

So you need to use Dependency injection because phpcs is telling you so ... here is an example.

<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides a 'FeedbackLinkBlock' block.
 *
 * @Block(
 *  id = "feedback_link_block",
 *  admin_label = @Translation("Feedback link block"),
 * )
 */
class FeedbackLinkBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Drupal\Core\Path\CurrentPathStack definition.
   *
   * @var \Drupal\Core\Path\CurrentPathStack
   */
  protected $pathCurrent;

  /**
   * Construct.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   */
  public function __construct(
        array $configuration,
        $plugin_id,
        $plugin_definition,
        CurrentPathStack $path_current
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->pathCurrent = $path_current;
  }

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

  /**
   * {@inheritdoc}
   */
  public function build() {
    $path = $this->pathCurrent->getPath();
    $options = [
      'query'      => ['path' => $path],
      'fragment'   => 'form',
      'attributes' => ['class' => ['btn', 'btn-info']],
      'absolute'   => TRUE,
    ];
    $link = Link::fromTextAndUrl($this->t('Feedback'), Url::fromUri('internal:/feedback', $options))->toString();

    $build = [];
    $build['#cache'] = ['max-age' => -1];

    $build['feedback_link_block']['#markup'] = $link;

    return $build;
  }

}

Category: