drupal 9 dependendency injection code example

Example: drupal 9 custom blocks dependency injection

/**
 * @file
 * Contains \Drupal\mymod\Plugin\Block\MyModMyStoreProductsStatusBlock
 */

namespace Drupal\mymod\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\mymod\StoreService;
use Symfony\Component\DependencyInjection\ContainerInterface;


/**
 * Provides a product status block for the store portal.
 * 
 * @Block(
 *   id = "mymod_my_store_products_status_block",
 *   admin_label = @Translation("My Store Products Status Block")
 * )
 */

class MyModMyStoreProductsStatusBlock extends BlockBase implements ContainerFactoryPluginInterface {
  // store service
  protected $ss = NULL;
  
  /*
   * static create function provided by the ContainerFactoryPluginInterface.
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('mymod.store_mgr')
    );
  }
  
  /*
   * BlockBase plugin constructor that's expecting the StoreService object provided by create().
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, StoreService $ss) {
    // instantiate the BlockBase parent first
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    
    // then save the store service passed to this constructor via dependency injection
    $this->ss = $ss;
  }
  
  /*
   * return the render array with the vals provided by the injected store service.
   */
  public function build() {
    return [
      '#theme' => 'mymod_mystore_products_status_block',
      '#n_total' => $this->ss->getTotalCount(),
      '#n_active' => $this->ss->getActiveCount(),
      '#sales_mtd' => $this->ss->getSalesMTD(),
      '#n_products_sold' => $this->ss->getTotalSoldCount()
    ];
  }
}

Tags:

Php Example