Last active
April 8, 2022 08:18
-
-
Save gregmercer/4973fca9c9fe0ee63b8db5556a208168 to your computer and use it in GitHub Desktop.
D8 - Services with Dependency Injection Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For entity query, we can use getQuery from entityTypeManager.
https://www.drupal.org/node/2849874