SlideShare a Scribd company logo
Drupal 8 Services
Phil Norton
Drupal::service('thing');
Wrap objects.
Define a common interface.
Dependency Injection.
Powerful.
Certified awesome.
uuid
date
queue
cache
menu
translation
entity
config
cron
renderer
path
route
file_system
plugin
$pathManager = Drupal::service('path.alias_manager');
$path = 'somepath';
$normal_path = $pathManager->getPathByAlias($path);
$normal_path = Drupal::service('path.alias_manager')
->getPathByAlias('somepath');
Services are defined in yml files
<module>.services.yml
queue.database:
class: DrupalCoreQueueQueueDatabaseFactory
arguments: ['@database']
path.alias_whitelist:
class: DrupalCorePathAliasWhitelist
tags:
- { name: needs_destruction }
arguments: [path_alias_whitelist, '@cache.bootstrap', '@lock', '@state', '@path.alias_storage']
path.alias_manager:
class: DrupalCorePathAliasManager
arguments: ['@path.alias_storage', '@path.alias_whitelist', '@language_manager', '@cache.data']
path.current:
class: DrupalCorePathCurrentPathStack
arguments: ['@request_stack']
Drupal 8 Services
Altering Services
Problem: Shield module prevents testing of API service on
staging website.
Solution: Poke a hole in the shield!
Module shield_override
shield_override.info.yml
src/ShieldOverrideServiceProvider.php
src/ShieldOverride.php
<?php
namespace Drupalshield_override;
use DrupalCoreDependencyInjectionContainerBuilder;
use DrupalCoreDependencyInjectionServiceProviderBase;
class ShieldOverrideServiceProvider extends ServiceProviderBase {
public function alter(ContainerBuilder $container) {
// Decorate the shield module to prevent it from triggering on certain
// routes.
$definition = $container->getDefinition('shield.middleware');
$definition->setClass('Drupalshield_overrideShieldOverride');
}
}
namespace Drupalshield_override;
use DrupalshieldShieldMiddleware;
use SymfonyComponentHttpFoundationRequest;
class ShieldOverride extends ShieldMiddleware {
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
// Get the current request URI.
$currentPath = $request->getRequestUri();
// Get the current method (e.g. GET or POST).
$currentMethod = $request->getMethod();
if (($currentMethod == 'POST' || $currentMethod == 'GET')
&& strstr($currentPath, '/the/soap/service/path) !== FALSE) {
// If we are attempting to access the soap controller via a post HTTP
// method then handle the request without invoking the Shield module.
return $this->httpKernel->handle($request, $type, $catch);
}
// Always handle the request using the default Shield behaviour.
return parent::handle($request, $type, $catch);
}
}
Create Your Own
<module>.services.yml
services:
<service name>:
class: Drupal<full namespace of service class>
arguments: ['@config.factory']
PCA Predict Module
services:
pcapredict:
class: Drupalpcapredict_integrationPcaPredictPcaPredict
arguments: ['@config.factory']
namespace Drupalpcapredict_integrationPcaPredict;
use DrupalCoreConfigConfigFactoryInterface;
use Drupalpcapredict_integrationPcaPredictPcaPredictInterface;
class PcaPredict implements PcaPredictInterface {
protected $pcaPredictKey;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->pcaPredictKey = $config_factory->get('pcapredict_integration.settings')->get('pcapredict_apikey');
}
public function find(array $values, $type = 'json') {
// Load data from the API.
}
public function retrieve(array $values, $type = 'json') {
// Load data from the API.
}
}
Problem: Testing PCA Predict needs an API account and
costs money per transaction.
Solution: Create a service override that doesn’t use the API.
New module called PCA Predict integration stub
pcapredict_integration_stub.info.yml
src/PcaPredictIntegrationStubServiceProvider.php
src/PcaPredict/PcaPredictStub.php
namespace Drupalpcapredict_integration_stub;
use DrupalCoreDependencyInjectionContainerBuilder;
use DrupalCoreDependencyInjectionServiceProviderBase;
class PcaPredictIntegrationStubServiceProvider extends ServiceProviderBase {
public function alter(ContainerBuilder $container) {
// Override the PcaPredict class with a new class.
$definition = $container->getDefinition('pcapredict');
$definition->setClass('Drupalpcapredict_integration_stubPcaPredictPcaPredictStub');
}
}
namespace Drupalpcapredict_integration_stubPcaPredict;
use Drupalpcapredict_integrationPcaPredictPcaPredictInterface;
use DrupalCoreConfigConfigFactoryInterface;
class PcaPredictStub implements PcaPredictInterface {
protected $pcaPredictKey;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->pcaPredictKey = $config_factory->get('pcapredict_integration.settings')->get('pcapredict_apikey');
}
public function find(array $values, $type = 'json') {
// Load data from a CSV file.
}
public function retrieve(array $values, $type = 'json') {
// Load data from a CSV file.
}
}
find() / retrieve()
API
Address finder
find() / retrieve() Address finder
Resources
Documentation
https://api.drupal.org/api/drupal/core%21core.api.php/group/container/8.3.x
List of all services
https://api.drupal.org/api/drupal/services

More Related Content

PDF
Drupal 8 Services And Dependency Injection
PDF
Getting Into Drupal 8 Configuration
PPTX
Becoming A Drupal Master Builder
PDF
Drupal 8 Configuration Management
PPTX
Migrate yourself. code -> module -> mind
PPTX
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
PDF
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
PDF
TurboGears2 Pluggable Applications
Drupal 8 Services And Dependency Injection
Getting Into Drupal 8 Configuration
Becoming A Drupal Master Builder
Drupal 8 Configuration Management
Migrate yourself. code -> module -> mind
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
TurboGears2 Pluggable Applications

What's hot (20)

KEY
CodeIgniter 3.0
PDF
Django Multi-DB in Anger
PPT
Multi Tenancy With Python and Django
PDF
Spring 4 - A&BP CC
PDF
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)
PDF
Head First Zend Framework - Part 1 Project & Application
PDF
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)
PPTX
WordPress Plugin development
PDF
Getting to The Loop - London Wordpress Meetup July 28th
PDF
Managing themes and server environments with extensible configuration arrays
PDF
Using RequireJS with CakePHP
ODP
Zend Framework 1.9 Setup & Using Zend_Tool
PDF
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
KEY
JavaScript in Drupal 7: What developers need to know
PDF
Full Stack Toronto - the 3R Stack
PDF
Introducing Assetic: Asset Management for PHP 5.3
PDF
Drupal 8 Configuration Management with Features
PDF
Staying Sane with Drupal NEPHP
PPTX
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
PPTX
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
CodeIgniter 3.0
Django Multi-DB in Anger
Multi Tenancy With Python and Django
Spring 4 - A&BP CC
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)
Head First Zend Framework - Part 1 Project & Application
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)
WordPress Plugin development
Getting to The Loop - London Wordpress Meetup July 28th
Managing themes and server environments with extensible configuration arrays
Using RequireJS with CakePHP
Zend Framework 1.9 Setup & Using Zend_Tool
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
JavaScript in Drupal 7: What developers need to know
Full Stack Toronto - the 3R Stack
Introducing Assetic: Asset Management for PHP 5.3
Drupal 8 Configuration Management with Features
Staying Sane with Drupal NEPHP
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
Ad

Similar to Drupal 8 Services (20)

PDF
ZF2 for the ZF1 Developer
PDF
Drupal 7 database api
PPTX
Routing in Drupal 8
PPTX
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
PPTX
Drupal 8 migrate!
PDF
2023 - Drupalcon - How Drupal builds your pages
PDF
Drupalcon 2023 - How Drupal builds your pages.pdf
PDF
Web applications with Catalyst
KEY
Yii Introduction
PDF
Symfony2 - from the trenches
PPTX
Debugging in drupal 8
PDF
Symfony2 from the Trenches
PDF
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
PDF
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
PDF
Lviv 2013 d7 vs d8
PDF
Zend Framework 2 - Basic Components
PDF
Lviv 2013 d7 vs d8
PDF
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
ZIP
What's new in the Drupal 7 API?
PPTX
8 things to know about theming in drupal 8
ZF2 for the ZF1 Developer
Drupal 7 database api
Routing in Drupal 8
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Drupal 8 migrate!
2023 - Drupalcon - How Drupal builds your pages
Drupalcon 2023 - How Drupal builds your pages.pdf
Web applications with Catalyst
Yii Introduction
Symfony2 - from the trenches
Debugging in drupal 8
Symfony2 from the Trenches
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
Lviv 2013 d7 vs d8
Zend Framework 2 - Basic Components
Lviv 2013 d7 vs d8
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
What's new in the Drupal 7 API?
8 things to know about theming in drupal 8
Ad

More from Philip Norton (9)

PDF
ReactPHP
PDF
Webform and Drupal 8
PDF
Acquia Drupal Certification
PDF
Drupal Performance : DrupalCamp North
PPT
Getting Started With Jenkins And Drupal
PDF
Drupal theming
PDF
ODP
Making The Drupal Pill Easier To Swallow
ODP
Drupal 7 Queues
ReactPHP
Webform and Drupal 8
Acquia Drupal Certification
Drupal Performance : DrupalCamp North
Getting Started With Jenkins And Drupal
Drupal theming
Making The Drupal Pill Easier To Swallow
Drupal 7 Queues

Recently uploaded (20)

PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Big Data Technologies - Introduction.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Spectral efficient network and resource selection model in 5G networks
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Big Data Technologies - Introduction.pptx
Encapsulation theory and applications.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.
Approach and Philosophy of On baking technology
Encapsulation_ Review paper, used for researhc scholars
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Monthly Chronicles - July 2025

Drupal 8 Services