commit 899c89645555c46400801beecffdfac80a57c0cc Author: Oliver Davies Date: Wed Jan 9 14:13:07 2019 +0000 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..4f9e9bc --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# Autowire Example + +An example module to demonstrate autowiring service classes in Drupal 8, as +well as how to define Controllers as Services. diff --git a/autowire_example.info.yml b/autowire_example.info.yml new file mode 100644 index 0000000..a14949b --- /dev/null +++ b/autowire_example.info.yml @@ -0,0 +1,5 @@ +name: 'Autowire Example' +type: module +description: 'An example module to demonstrate autowiring in Drupal 8.' +core: 8.x +package: 'Example modules' diff --git a/autowire_example.routing.yml b/autowire_example.routing.yml new file mode 100644 index 0000000..7883ef4 --- /dev/null +++ b/autowire_example.routing.yml @@ -0,0 +1,6 @@ +autowire_example.user_count: + path: '/user-count' + defaults: + _controller: 'Drupal\autowire_example\Controller\ExampleController::__invoke' + requirements: + _access: 'TRUE' diff --git a/autowire_example.services.yml b/autowire_example.services.yml new file mode 100644 index 0000000..edab41d --- /dev/null +++ b/autowire_example.services.yml @@ -0,0 +1,6 @@ +services: + Drupal\autowire_example\Service\UserCounter: + autowire: true + + Drupal\autowire_example\Controller\ExampleController: + autowire: true diff --git a/src/Controller/ExampleController.php b/src/Controller/ExampleController.php new file mode 100644 index 0000000..b945018 --- /dev/null +++ b/src/Controller/ExampleController.php @@ -0,0 +1,48 @@ +userCounter = $user_counter; + } + + /** + * Display the username of the current user. + * + * @return array + * A render array. + */ + public function __invoke() { + return [ + '#markup' => $this->formatPlural( + number_format($this->userCounter->getActiveUserCount()), + 'This site has 1 active user.', + 'This site has @count active users.' + ) + ]; + } + +} diff --git a/src/Service/UserCounter.php b/src/Service/UserCounter.php new file mode 100644 index 0000000..d4edc15 --- /dev/null +++ b/src/Service/UserCounter.php @@ -0,0 +1,46 @@ +userStorage = $entity_type_manager->getStorage('user'); + } + + /** + * Count the active users. + * + * @return integer + * The number of active users. + */ + public function getActiveUserCount() { + return (int) $this->userStorage + ->getQuery() + ->condition('status', 1) + ->count() + ->execute(); + } + +}