Skip to content

Instantly share code, notes, and snippets.

@gregmercer
Created January 16, 2019 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregmercer/64f9f36e4adadda6671868bf8821f15b to your computer and use it in GitHub Desktop.
Save gregmercer/64f9f36e4adadda6671868bf8821f15b to your computer and use it in GitHub Desktop.
D8 - Dependency Injection - Controllers Example
D8 - Dependency Injection - Controllers
Key ContainerInterface method - create()
public static function create(ContainerInterface $container)
and use of $container->get()
...
lightning-8/modules/custom/basic/src/Controller/BasicController.php
<?php
namespace Drupal\basic\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\basic\BasicRecipeService;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Session\AccountProxy;
/**
* Basic controller.
*/
class BasicController extends ControllerBase {
private $recipeService;
protected $configFactory;
protected $currentUser;
public static function create(ContainerInterface $container) {
return new static(
$container->get('basic.basic_recipes'),
$container->get('config.factory'),
$container->get('current_user')
);
}
public function __construct(BasicRecipeService $recipeService, ConfigFactory $configFactory, AccountProxy $currentUser) {
$this->recipeService = $recipeService;
$this->configFactory = $configFactory;
$this->currentUser = $currentUser;
}
public function recipeList() {
kint($this->recipeService->getRecipes()); die();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment