Drupal - Dependency injection to load node data
The controller base class provides the method entityTypeManager()
which gets the service with the same name from the container the first time you use it. You can use this service to get the node storage:
$node_storage = $this->entityTypeManager()->getStorage('node');
and then load the node:
$node = $node_storage->load($nid);
I'm not a 100% sure but this is how I got it working for a block (the node(s) didn't come from context):
<?php
namespace Drupal\MYMODULE\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Provides a 'My Block' Block.
*
* @Block(
* id = "my_block",
* admin_label = @Translation("My Block"),
* )
*/
class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new MyBlock.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param array $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$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('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$node_storage = $this->entityTypeManager->getStorage('node');
$node = $node_storage->load(1);
return [
'#markup' => $node->getTitle(),
];
}
}