Saturday 16 March 2019

Dependency Injection in custom rest resource API

Use Dependency Injection in Custom Rest Resource

In previous post, created custom rest resource, Now I have to use dependency injection to inject services which are used with the help of Global service container like \Drupal::entityQuery('node')->execute()
To replace this, we use dependency injection. So see below updated code of previously created custom service.
<?php

/**
 * @file
 * Contains Drupal\firstcustommodule\Plugin\rest\resource\nodesTitleGetRestResource
 */

namespace Drupal\firstcustommodule\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\node\Entity\Node;

/**
 * Provides REST API for nodes title.
 *
 * @RestResource(
 *   id = "get_nodes_title_rest_resource",
 *   label = @Translation("Nodes Title API"),
 *   uri_paths = {
 *     "canonical" = "/api/nodes/title"
 *   }
 * )
 */
class nodesTitleGetRestResource extends ResourceBase {

 /**
   * Request stack.
   *
   * @var Symfony\Component\HttpFoundation\RequestStack
   */
  protected $request;

  /**
   * The logger channel factory.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
   protected $entityQuery;

 /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration, $plugin_id, $plugin_definition, $container->getParameter('serializer.formats'), $container->get('logger.factory')->get('rest'), $container->get('request_stack'), $container->get('entity.query')
    );
  }

 /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @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 array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param Symfony\Component\HttpFoundation\RequestStack $request
   *   Request params instance.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, RequestStack $request, QueryFactory $entity_query = NULL) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->request = $request->getCurrentRequest();
$this->entityQuery = $entity_query;
  }

  /**
   * Responds to entity GET requests.
   *
   * @return \Drupal\rest\ResourceResponse
   *   Returning rest resource.
   */
  public function get() {
    $nids = $this->entityQuery->get('node')->execute();
    $nodes =  Node::loadMultiple($nids);
    $node_titles = [];
    foreach ($nodes as $node) {
      $node_titles[$node->id()] = $node->getTitle();
    }
    return new ResourceResponse($node_titles);
  }
}

Explanation:







No comments:

Post a Comment