Created
January 16, 2019 18:32
-
-
Save gregmercer/64f9f36e4adadda6671868bf8821f15b to your computer and use it in GitHub Desktop.
D8 - Dependency Injection - Controllers 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 - 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