1

I have class named Book.

class Popups
{
  private $entityQuery;
  private $entityTypeManager;

  public function __construct(QueryFactory $entityQuery, EntityTypeManagerInterface $entity_type_manager) {
    $this->entityQuery = $entityQuery;
    $this->entityTypeManager = $entity_type_manager;
  }



public function read($cid)
  {
    $nodes = $this->entityTypeManager->getStorage('node')->loadByProperties(['type' => 'book', 'cid' => $cid ]);

    return $nodes;
  }

}

Now I have books.module file where I need to call read method; how to call that method

$book = new Book();  // what param should i pass here
$book->read($cid)
4
  • Why not add the class to mymodule.services.yml and inject the core services there?
    – 4uk4
    Sep 3, 2019 at 12:18
  • That won’t work because the constructor is expecting arguments. Register this class as a service, and call it with \Drupal::service() instead.
    – Kevin
    Sep 3, 2019 at 12:19
  • @4k4 there are some database related queries written in read function with searvices and in .module file I only need to call that read method.
    – mintra
    Sep 3, 2019 at 12:20
  • 1
    I don't understand why database queries would be a reason not to use a service.
    – 4uk4
    Sep 3, 2019 at 12:31

1 Answer 1

7

Add the class to mymodule.services.yml and inject the core services there:

mymodule.services.yml

services:
  mymodule.book:
    class: Drupal\mymodule\Book
    arguments: ['@entity.query', '@entity_type.manager']

Then use the service in procedural code:

\Drupal::service('mymodule.book')->read($cid)
4
  • I don't wish to in this way my question was how to call controller function in module
    – mintra
    Sep 3, 2019 at 12:53
  • At the moment the function is not a controller. However, if you want to add a controller method to the class, you can do this in a service as well, see drupal.org/docs/8/api/routing-system/structure-of-routes. Which is IMHO a better way for dependency injection anyway, and you can use the service resources in multiple places, without the need to create multiple instances.
    – 4uk4
    Sep 3, 2019 at 12:59
  • I don't wish to in this way this is how its done, you don't new Class() anything in procedural - this will resolve dependencies and take care of instantiation for you.
    – Kevin
    Sep 3, 2019 at 15:42
  • You may not want to do it this way, but you've come on a Drupal QA site and asked a Drupal question, to which you've been given a Drupal answer. If you want a non-Drupal way, you're likely on your own to find a solution.
    – Jaypan
    Sep 3, 2019 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.