Skip to content

Instantly share code, notes, and snippets.

@gregmercer
Last active April 8, 2022 08:18
Show Gist options
  • Save gregmercer/4973fca9c9fe0ee63b8db5556a208168 to your computer and use it in GitHub Desktop.
Save gregmercer/4973fca9c9fe0ee63b8db5556a208168 to your computer and use it in GitHub Desktop.
D8 - Services with Dependency Injection Example
D8 - Services with Dependency Injection
...
lightning-8/modules/custom/basic/basic.services.yml
services:
basic.basic_hero_articles:
class: Drupal\basic\BasicArticleService
basic.basic_recipes:
class: Drupal\basic\BasicRecipeService
arguments: ['@entity.query', '@entity.manager']
...
lightning-8/modules/custom/basic/src/BasicRecipeService.php
<?php
namespace Drupal\basic;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityManager;
/**
* Our basic recipes service
*/
class BasicRecipeService {
private $entityQuery;
private $entityManager;
public function __construct(QueryFactory $entityQuery, EntityManager $entityManager) {
$this->entityQuery = $entityQuery;
$this->entityManager = $entityManager;
}
/**
* Methood for getting the recipes
*/
public function getRecipes() {
$recipesNids = $this->entityQuery->get('node')->condition('type', 'recipe')->execute();
return $this->entityManager->getStorage('node')->loadMultiple($recipesNids);
}
}
...
Test using devel/php page
$basicRecipeService = Drupal::service("basic.basic_recipes");
kint($basicRecipeService->getRecipes()); die();
@zuhairkareem
Copy link

For entity query, we can use getQuery from entityTypeManager.

$query = $this->entityTypeManager->getStorage('node')->getQuery(); 

https://www.drupal.org/node/2849874

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment