Call core services of Drupal 8 via the service container


It is not very good way to call Drupal core services directly in the class. Try to avoid such code in your code. Intead of doing that you can inject core services through service containner. Following code will help you to know how you should do that.

<?php

  /**
   * Database Service Object.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;


  public function __construct(Connection $connection) {
    $this->connection = $connection;
  }

  /**
   * {@inheritdoc}
   */
  public static function create() {
    return new static($container->get('database'), $container->get('entity.manager')->getStorage('taxonomy_vocabulary')
    );


  public function validatefunction($arg) { 
    $select = $this->connection->select('taxonomy_index', 'ti')->fields('ti', array('tid'));
    $result = $select->execute();
   }
}

So intead of calling $connection = \Drupal::database(); , you should inject core services into your class visa container service.

Details code you can found :-  http://cgit.drupalcode.org/similarterms/tree/views/similarterms_handler_argument_node_nid.inc

Helpful information to read :- https://www.drupal.org/node/2133171

Advertisements

  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: