Skip to content

Instantly share code, notes, and snippets.

@Jaesin
Created May 15, 2017 16:02
Show Gist options
  • Save Jaesin/51e2c0c7b51de6e23b9e94acdd3c8f2e to your computer and use it in GitHub Desktop.
Save Jaesin/51e2c0c7b51de6e23b9e94acdd3c8f2e to your computer and use it in GitHub Desktop.
Autowiring services in Drupal 8
name: Example
type: module
description: Provides a service to demonstrate service autowiring.
package: Example
core: 8.x
services:
example.fancy_service:
class: Drupal\example\FancyService
autowire: true
<?php
/**
* @file `src/FancyService.php`
*
* Fancy service provides lyric segments from Iggy Azalea's song, "Fancy".
*/
namespace Drupal\example;
use Drupal\Core\Language\LanguageManagerInterface;
class FancyService {
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $language_manager;
/**
* Constructs a new FancyService.
*
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
*/
public function __construct(LanguageManagerInterface $language_manager) {
$this->language_manager = $language_manager;
}
/**
* Get fancy lyrics.
*
* @return string
*/
public function getFancy() {
$lang_code = $this->language_manager->getCurrentLanguage()->getId();
if ($lang_code === 'en') {
return "I'm so fancy. You already know.";
} else {
return "Estoy en el carril rápido. De LA a Tokio.";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment