Created
November 19, 2021 14:23
-
-
Save levmyshkin/dfd32f087268dfd90e3db766daaeca38 to your computer and use it in GitHub Desktop.
Drupal Dependency Injection in Block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// /modules/custom/drupalbook/src/Plugin/Block/CartBlock.php | |
namespace Drupal\drupalbook\Plugin\Block; | |
use Drupal\commerce_cart\CartProviderInterface; | |
use Drupal\Core\Block\BlockBase; | |
use Drupal\Core\Entity\EntityTypeManagerInterface; | |
use Drupal\Core\Plugin\ContainerFactoryPluginInterface; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
/** | |
* Provides a cart block. | |
* | |
* @Block( | |
* id = "commerce_cart", | |
* admin_label = @Translation("Cart"), | |
* category = @Translation("Commerce") | |
* ) | |
*/ | |
class CartBlock extends BlockBase implements ContainerFactoryPluginInterface { | |
/** | |
* The cart provider. | |
* | |
* @var \Drupal\commerce_cart\CartProviderInterface | |
*/ | |
protected $cartProvider; | |
/** | |
* The entity type manager. | |
* | |
* @var \Drupal\Core\Entity\EntityTypeManagerInterface | |
*/ | |
protected $entityTypeManager; | |
/** | |
* Constructs a new CartBlock. | |
* | |
* @param array $configuration | |
* A configuration array containing information about the plugin instance. | |
* @param string $plugin_id | |
* The plugin ID for the plugin instance. | |
* @param mixed $plugin_definition | |
* The plugin implementation definition. | |
* @param \Drupal\commerce_cart\CartProviderInterface $cart_provider | |
* The cart provider. | |
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager | |
* The entity type manager. | |
*/ | |
public function __construct(array $configuration, $plugin_id, $plugin_definition, CartProviderInterface $cart_provider, EntityTypeManagerInterface $entity_type_manager) { | |
parent::__construct($configuration, $plugin_id, $plugin_definition); | |
$this->cartProvider = $cart_provider; | |
$this->entityTypeManager = $entity_type_manager; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { | |
return new static( | |
$configuration, | |
$plugin_id, | |
$plugin_definition, | |
$container->get('commerce_cart.cart_provider'), | |
$container->get('entity_type.manager') | |
); | |
} | |
/** | |
* Builds the cart block. | |
* | |
* @return array | |
* A render array. | |
*/ | |
public function build() { | |
... | |
/** @var \Drupal\commerce_order\Entity\OrderInterface[] $carts */ | |
$carts = $this->cartProvider->getCarts(); | |
... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment