drupal 9 dependendency injection code example
Example: drupal 9 custom blocks dependency injection
namespace Drupal\mymod\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\mymod\StoreService;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyModMyStoreProductsStatusBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $ss = NULL;
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')
);
}
public function __construct(array $configuration, $plugin_id, $plugin_definition, StoreService $ss) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->ss = $ss;
}
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()
];
}
}