SlideShare a Scribd company logo
A Deep Dive into Drupal
8 Routing
DrupalCamp Mumbai
April 1, 2017
Naveen Valecha
About me
● Drupal: naveenvalecha
● Git Administer on Drupal.org
● Site Maintainer of groups.drupal.org
● Twitter: @_naveenvalecha_
● Web: https://www.valechatech.net
● Drupal 5,6,7,8
Agenda
● What are Routes. Why we need them?
● Routes and Controllers
● Access checking on routes
● Custom Access Checkers
● CSRF Prevention on routes
● Altering routes
● Dynamic Routes
● Parameter Upcasting
Routing System
● hook_menu to Symfony2 routing
● Replace paths with route names for rendering
links
● Converting all page callbacks to controllers
● New breadcrumb system, new menu link system,
conversion of local tasks and actions to plugins
Routing System - Cont.
● menu links, local tasks, local actions, contextual
links
● Split all the pieces from hook_menu into YAML
files finally
● module.routing.yml module.links.menu.yml
● module.links.task.yml module.links.action.yml
● module.contextual.yml
hook_menu to Symfony Routing
● PHP array to multiple yaml files
● Performance improvements
● Developer Experience(DX)
● Clean Code
● Procedural to Object Oriented(OO)
D7 hook_menu
$items['admin/appearance/settings'] = array(
'title' => 'Settings',
'description' => 'Configure default and theme specific settings.',
'page callback' => 'drupal_get_form',
'page arguments' => array('system_theme_settings'),
'access arguments' => array('administer themes'),
'type' => MENU_LOCAL_TASK,
'file' => 'system.admin.inc',
'weight' => 20,
);
D8 system.routing.yml
system.theme_settings:
path: '/admin/appearance/settings'
defaults:
_form: 'DrupalsystemFormThemeSettingsForm'
_title: 'Appearance settings'
requirements:
_permission: 'administer themes'
D8 system.links.task.yml
system.theme_settings:
route_name: system.theme_settings
title: 'Settings'
base_route: system.themes_page
weight: 100
Route
● A route is a path which is defined for Drupal to
return some sort of content on. For example, the
default front page, '/node' is a route.
● Use mm.routing.yml for defining routes
Routes and Controllers
● The routing system is responsible for matching
paths to controllers, and you define those
relations in routes. You can pass on additional
information to your controllers in the route.
Access checking is integrated as well.
Route - Slug
entity.node.preview:
path: '/node/preview/{node_preview}/{view_mode_id}'
defaults:
_controller: 'DrupalnodeControllerNodePreviewController::view'
_title_callback: 'DrupalnodeControllerNodePreviewController::title'
requirements:
_node_preview_access: '{node_preview}'
options:
parameters:
node_preview:
type: 'node_preview'
/**
* Defines a controller to render a single node in preview.
*/
class NodePreviewController extends EntityViewController {
/**
* {@inheritdoc}
*/
public function view(EntityInterface $node_preview, $view_mode_id =
'full', $langcode = NULL) {
$node_preview->preview_view_mode = $view_mode_id;
$build = parent::view($node_preview, $view_mode_id);
return $build;
}
}
example.content:
path: '/example'
defaults:
_controller:
'DrupalexampleControllerExampleController::content'
custom_arg: 12
requirements:
_permission: 'access content'
// ...
public function content(Request $request, $custom_arg) {
// Now can use $custom_arg (which will get 12 here) and $request.
}
Routes Structure
● Path(*): /node/preview/{node_preview}/{view_mode_id}
● defaults(*)
○ _controller:
DrupalnodeControllerNodePreviewController::view
○ _form: DrupalCoreFormFormInterface
○ _entity_view, _entity_form:
○ _title(optional), _title_context(optional),
_title_callback(optional)
Routes Structure
● methods(optional)
● Requirements
○ _permission, _role, _access, _entity_access,
_custom_access, _format,
_content_type_format
○ _module_dependencies
○ _csrf_token
Access checking
Permission
requirements:
_permission: 'administer content types'
Role
requirements:
_role: 'administrator'
Access checking - Custom
class NodeRevisionAccessCheck implements AccessInterface {
public function access(Route $route, AccountInterface $account, $node_revision =
NULL, NodeInterface $node = NULL) {
if ($node_revision) {
$node = $this->nodeStorage->loadRevision($node_revision);
}
$operation = $route->getRequirement('_access_node_revision');
return AccessResult::allowedIf($node && $this->checkAccess($node, $account,
$operation))->cachePerPermissions()->addCacheableDependency($node);
}
}
Route - CSRF Protection
aggregator.feed_refresh:
path: '/admin/config/services/aggregator/update/{aggregator_feed}'
defaults:
_controller:
'DrupalaggregatorControllerAggregatorController::feedRefresh'
_title: 'Update items'
requirements:
_permission: 'administer news feeds'
_csrf_token: 'TRUE'
Routes - Altering
class NodeAdminRouteSubscriber extends RouteSubscriberBase {
protected function alterRoutes(RouteCollection $collection) {
if ($this->configFactory->get('node.settings')->get('use_admin_theme')) {
foreach ($collection->all() as $route) {
if ($route->hasOption('_node_operation_route')) {
$route->setOption('_admin_route', TRUE);
}
}
}
}
}
Dynamic Routes
Image.routing.yml
route_callbacks:
- 'DrupalimageRoutingImageStyleRoutes::routes'
Dynamic Routes - Cont.
class ImageStyleRoutes implements ContainerInjectionInterface {
public function routes() {
$routes = [];
$directory_path = $this->streamWrapperManager->getViaScheme('public')->getDirectoryPath();
$routes['image.style_public'] = new Route(
'/' . $directory_path . '/styles/{image_style}/{scheme}',
[ '_controller' => 'DrupalimageControllerImageStyleDownloadController::deliver', ],
[ '_access' => 'TRUE', ]
);
return $routes;
}
}
Route-Parameter Upcasting
entity.node.preview:
path: '/node/preview/{node_preview}/{view_mode_id}'
defaults:
_controller: 'DrupalnodeControllerNodePreviewController::view'
_title_callback: 'DrupalnodeControllerNodePreviewController::title'
requirements:
_node_preview_access: '{node_preview}'
options:
parameters:
node_preview:
type: 'node_preview'
Route-Parameter Upcasting Cont.
node.services.yml
node_preview:
class: DrupalnodeParamConverterNodePreviewConverter
arguments: ['@user.private_tempstore']
tags:
- { name: paramconverter }
lazy: true
Route-Parameter Upcasting Cont.
class NodePreviewConverter implements ParamConverterInterface {
public function convert($value, $definition, $name, array $defaults) {
$store = $this->tempStoreFactory->get('node_preview');
if ($form_state = $store->get($value)) {
return $form_state->getFormObject()->getEntity();
}
}
public function applies($definition, $name, Route $route) {
if (!empty($definition['type']) && $definition['type'] == 'node_preview') {
return TRUE;
}
return FALSE;
}
What’s for Drupal 9?
● Consider having a single class for Match Dumper,
Route Provider and Route Builder
● Automatically unserialize request data and
serialize outgoing data
References
● http://symfony.com/doc/current/components/
routing.html
● https://www.drupal.org/docs/8/api/routing-syste
m
Questions?
THANK YOU!

More Related Content

What's hot

2.routing in zend framework 3
2.routing in zend framework 32.routing in zend framework 3
2.routing in zend framework 3
Razvan Raducanu, PhD
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?
Tomasz Bak
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
Gary Hockin
 
Lightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with BrowserifyLightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with Browserify
crgwbr
 
Your first d8 module
Your first d8 moduleYour first d8 module
Your first d8 module
tedbow
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
Robert Munteanu
 
Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8
Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8
Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8
Vladimir Roudakov
 
livedoor blogのsorryサーバの話 #study2study
livedoor blogのsorryサーバの話 #study2studylivedoor blogのsorryサーバの話 #study2study
livedoor blogのsorryサーバの話 #study2study
SATOSHI TAGOMORI
 
Introduce of the parallel distributed Crawler with scraping Dynamic HTML
Introduce of the parallel distributed Crawler with scraping Dynamic HTMLIntroduce of the parallel distributed Crawler with scraping Dynamic HTML
Introduce of the parallel distributed Crawler with scraping Dynamic HTML
Kei Shiratsuchi
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
Acquisio
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
aglemann
 
How to Use the Command Line to Increase Speed of Development
How to Use the Command Line to Increase Speed of DevelopmentHow to Use the Command Line to Increase Speed of Development
How to Use the Command Line to Increase Speed of Development
Acquia
 
Backbone
BackboneBackbone
Backbone
Glenn De Backer
 
UI-Router
UI-RouterUI-Router
UI-Router
Loc Nguyen
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
katbailey
 
Angular JS Routing
Angular JS RoutingAngular JS Routing
Angular JS Routing
kennystoltz
 
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Acquia
 
Drupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of FrontendDrupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of Frontend
Acquia
 

What's hot (20)

2.routing in zend framework 3
2.routing in zend framework 32.routing in zend framework 3
2.routing in zend framework 3
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Lightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with BrowserifyLightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with Browserify
 
Your first d8 module
Your first d8 moduleYour first d8 module
Your first d8 module
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 
Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8
Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8
Brisbane Drupal meetup - 2016 Mar - Build module in Drupal 8
 
livedoor blogのsorryサーバの話 #study2study
livedoor blogのsorryサーバの話 #study2studylivedoor blogのsorryサーバの話 #study2study
livedoor blogのsorryサーバの話 #study2study
 
Pyramid
PyramidPyramid
Pyramid
 
Introduce of the parallel distributed Crawler with scraping Dynamic HTML
Introduce of the parallel distributed Crawler with scraping Dynamic HTMLIntroduce of the parallel distributed Crawler with scraping Dynamic HTML
Introduce of the parallel distributed Crawler with scraping Dynamic HTML
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
How to Use the Command Line to Increase Speed of Development
How to Use the Command Line to Increase Speed of DevelopmentHow to Use the Command Line to Increase Speed of Development
How to Use the Command Line to Increase Speed of Development
 
Backbone
BackboneBackbone
Backbone
 
UI-Router
UI-RouterUI-Router
UI-Router
 
Presentation
PresentationPresentation
Presentation
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Angular JS Routing
Angular JS RoutingAngular JS Routing
Angular JS Routing
 
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
 
Drupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of FrontendDrupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of Frontend
 

Viewers also liked

Google summer of code with drupal
Google summer of code with drupalGoogle summer of code with drupal
Google summer of code with drupal
Naveen Valecha
 
Hack proof your drupal site- DrupalCamp Hyderabad
Hack proof your drupal site- DrupalCamp HyderabadHack proof your drupal site- DrupalCamp Hyderabad
Hack proof your drupal site- DrupalCamp Hyderabad
Naveen Valecha
 
Tercera Trobada #Xatac5a Tarragona
Tercera Trobada #Xatac5a TarragonaTercera Trobada #Xatac5a Tarragona
Tercera Trobada #Xatac5a Tarragona
Neus Lorenzo
 
フェーズI/IIに置けるベイジアン・アダプティブ・メソッド
フェーズI/IIに置けるベイジアン・アダプティブ・メソッドフェーズI/IIに置けるベイジアン・アダプティブ・メソッド
フェーズI/IIに置けるベイジアン・アダプティブ・メソッド
Yoshitake Takebayashi
 
Marketing's important. But marketers often aren't.
Marketing's important. But marketers often aren't.Marketing's important. But marketers often aren't.
Marketing's important. But marketers often aren't.
London Business School
 
Immunisation against bacteria
Immunisation against bacteriaImmunisation against bacteria
Immunisation against bacteria
Rohit Satyam
 
Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...
Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...
Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...
India-EU Water Partnership
 
A Building Framework for the All Renewable Energy Future
A Building Framework for the All Renewable Energy FutureA Building Framework for the All Renewable Energy Future
A Building Framework for the All Renewable Energy Future
Bronwyn Barry
 
ARM Compute Library
ARM Compute LibraryARM Compute Library
ARM Compute Library
Mr. Vengineer
 
Biases in military history
Biases in military historyBiases in military history
Biases in military history
Agha A
 
In the DOM, no one will hear you scream
In the DOM, no one will hear you screamIn the DOM, no one will hear you scream
In the DOM, no one will hear you scream
Mario Heiderich
 
グローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめよう
グローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめようグローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめよう
グローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめよう
Teng Tokoro
 
Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~
Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~
Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~
Brocade
 
GroovyFX - Groove JavaFX
GroovyFX - Groove JavaFXGroovyFX - Groove JavaFX
GroovyFX - Groove JavaFX
sascha_klein
 
Alejandro Fernandez vs Luis Miguel
Alejandro Fernandez vs Luis MiguelAlejandro Fernandez vs Luis Miguel
Alejandro Fernandez vs Luis Miguel
Susana Gallardo
 
マイクロソフトが創る未来 医療編 20170401
マイクロソフトが創る未来 医療編 20170401マイクロソフトが創る未来 医療編 20170401
マイクロソフトが創る未来 医療編 20170401
Aya Tokura
 
Green Behavior
Green BehaviorGreen Behavior
Green Behavior
Alireza Ranjbar SHourabi
 
Elixir-Conf-Japan-2017-session-ohr486
Elixir-Conf-Japan-2017-session-ohr486Elixir-Conf-Japan-2017-session-ohr486
Elixir-Conf-Japan-2017-session-ohr486
Tsunenori Oohara
 
Top Artificial Intelligence (AI) Startups Disrupting Retail
Top Artificial Intelligence (AI) Startups Disrupting RetailTop Artificial Intelligence (AI) Startups Disrupting Retail
Top Artificial Intelligence (AI) Startups Disrupting Retail
NVIDIA
 
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
HubSpot
 

Viewers also liked (20)

Google summer of code with drupal
Google summer of code with drupalGoogle summer of code with drupal
Google summer of code with drupal
 
Hack proof your drupal site- DrupalCamp Hyderabad
Hack proof your drupal site- DrupalCamp HyderabadHack proof your drupal site- DrupalCamp Hyderabad
Hack proof your drupal site- DrupalCamp Hyderabad
 
Tercera Trobada #Xatac5a Tarragona
Tercera Trobada #Xatac5a TarragonaTercera Trobada #Xatac5a Tarragona
Tercera Trobada #Xatac5a Tarragona
 
フェーズI/IIに置けるベイジアン・アダプティブ・メソッド
フェーズI/IIに置けるベイジアン・アダプティブ・メソッドフェーズI/IIに置けるベイジアン・アダプティブ・メソッド
フェーズI/IIに置けるベイジアン・アダプティブ・メソッド
 
Marketing's important. But marketers often aren't.
Marketing's important. But marketers often aren't.Marketing's important. But marketers often aren't.
Marketing's important. But marketers often aren't.
 
Immunisation against bacteria
Immunisation against bacteriaImmunisation against bacteria
Immunisation against bacteria
 
Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...
Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...
Mr. Nitin bassi IEWP @ 2nd India-EU Water Forum @ World Sustainable Developme...
 
A Building Framework for the All Renewable Energy Future
A Building Framework for the All Renewable Energy FutureA Building Framework for the All Renewable Energy Future
A Building Framework for the All Renewable Energy Future
 
ARM Compute Library
ARM Compute LibraryARM Compute Library
ARM Compute Library
 
Biases in military history
Biases in military historyBiases in military history
Biases in military history
 
In the DOM, no one will hear you scream
In the DOM, no one will hear you screamIn the DOM, no one will hear you scream
In the DOM, no one will hear you scream
 
グローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめよう
グローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめようグローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめよう
グローバル理工人材のための今日から使える検索テクニック ―もう日本語でググるのはやめよう
 
Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~
Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~
Event-driven automation, DevOps way ~IoT時代の自動化、そのリアリティとは?~
 
GroovyFX - Groove JavaFX
GroovyFX - Groove JavaFXGroovyFX - Groove JavaFX
GroovyFX - Groove JavaFX
 
Alejandro Fernandez vs Luis Miguel
Alejandro Fernandez vs Luis MiguelAlejandro Fernandez vs Luis Miguel
Alejandro Fernandez vs Luis Miguel
 
マイクロソフトが創る未来 医療編 20170401
マイクロソフトが創る未来 医療編 20170401マイクロソフトが創る未来 医療編 20170401
マイクロソフトが創る未来 医療編 20170401
 
Green Behavior
Green BehaviorGreen Behavior
Green Behavior
 
Elixir-Conf-Japan-2017-session-ohr486
Elixir-Conf-Japan-2017-session-ohr486Elixir-Conf-Japan-2017-session-ohr486
Elixir-Conf-Japan-2017-session-ohr486
 
Top Artificial Intelligence (AI) Startups Disrupting Retail
Top Artificial Intelligence (AI) Startups Disrupting RetailTop Artificial Intelligence (AI) Startups Disrupting Retail
Top Artificial Intelligence (AI) Startups Disrupting Retail
 
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
 

Similar to A deep dive into Drupal 8 routing

Getting started with the Lupus Nuxt.js Drupal Stack
Getting started with the Lupus Nuxt.js Drupal StackGetting started with the Lupus Nuxt.js Drupal Stack
Getting started with the Lupus Nuxt.js Drupal Stack
nuppla
 
Drupal 8 Routing
Drupal 8 RoutingDrupal 8 Routing
Drupal 8 Routing
Yuriy Gerasimov
 
13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS 13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS
DrupalMumbai
 
AngularJS
AngularJSAngularJS
AngularJS
Pasi Manninen
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
Pavel Makhrinsky
 
Migrations
MigrationsMigrations
Migrations
Yaron Tal
 
Advanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareAdvanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshare
Opevel
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
Stéphane Bégaudeau
 
Server Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.jsServer Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.js
Jessie Barnett
 
Taking your module from Drupal 6 to Drupal 7
Taking your module from Drupal 6 to Drupal 7Taking your module from Drupal 6 to Drupal 7
Taking your module from Drupal 6 to Drupal 7
Phase2
 
Zend Framework Foundations
Zend Framework FoundationsZend Framework Foundations
Zend Framework Foundations
Chuck Reeves
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinADCI Solutions
 
Angular basicschat
Angular basicschatAngular basicschat
Angular basicschatYu Jin
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
Cornel Stefanache
 
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Samuel Solís Fuentes
 
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011camp_drupal_ua
 
Angular presentation
Angular presentationAngular presentation
Angular presentation
Matus Szabo
 
Zend Framework 2 - Basic Components
Zend Framework 2  - Basic ComponentsZend Framework 2  - Basic Components
Zend Framework 2 - Basic Components
Mateusz Tymek
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
Jeff Eaton
 

Similar to A deep dive into Drupal 8 routing (20)

Getting started with the Lupus Nuxt.js Drupal Stack
Getting started with the Lupus Nuxt.js Drupal StackGetting started with the Lupus Nuxt.js Drupal Stack
Getting started with the Lupus Nuxt.js Drupal Stack
 
Drupal 8 Routing
Drupal 8 RoutingDrupal 8 Routing
Drupal 8 Routing
 
13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS 13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS
 
что нового в мире Services
что нового в мире Servicesчто нового в мире Services
что нового в мире Services
 
AngularJS
AngularJSAngularJS
AngularJS
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Migrations
MigrationsMigrations
Migrations
 
Advanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareAdvanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshare
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Server Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.jsServer Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.js
 
Taking your module from Drupal 6 to Drupal 7
Taking your module from Drupal 6 to Drupal 7Taking your module from Drupal 6 to Drupal 7
Taking your module from Drupal 6 to Drupal 7
 
Zend Framework Foundations
Zend Framework FoundationsZend Framework Foundations
Zend Framework Foundations
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton Shubkin
 
Angular basicschat
Angular basicschatAngular basicschat
Angular basicschat
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
 
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
 
Angular presentation
Angular presentationAngular presentation
Angular presentation
 
Zend Framework 2 - Basic Components
Zend Framework 2  - Basic ComponentsZend Framework 2  - Basic Components
Zend Framework 2 - Basic Components
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 

Recently uploaded

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 

Recently uploaded (20)

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 

A deep dive into Drupal 8 routing

  • 1. A Deep Dive into Drupal 8 Routing DrupalCamp Mumbai April 1, 2017 Naveen Valecha
  • 2. About me ● Drupal: naveenvalecha ● Git Administer on Drupal.org ● Site Maintainer of groups.drupal.org ● Twitter: @_naveenvalecha_ ● Web: https://www.valechatech.net ● Drupal 5,6,7,8
  • 3. Agenda ● What are Routes. Why we need them? ● Routes and Controllers ● Access checking on routes ● Custom Access Checkers ● CSRF Prevention on routes ● Altering routes ● Dynamic Routes ● Parameter Upcasting
  • 4. Routing System ● hook_menu to Symfony2 routing ● Replace paths with route names for rendering links ● Converting all page callbacks to controllers ● New breadcrumb system, new menu link system, conversion of local tasks and actions to plugins
  • 5. Routing System - Cont. ● menu links, local tasks, local actions, contextual links ● Split all the pieces from hook_menu into YAML files finally ● module.routing.yml module.links.menu.yml ● module.links.task.yml module.links.action.yml ● module.contextual.yml
  • 6. hook_menu to Symfony Routing ● PHP array to multiple yaml files ● Performance improvements ● Developer Experience(DX) ● Clean Code ● Procedural to Object Oriented(OO)
  • 7. D7 hook_menu $items['admin/appearance/settings'] = array( 'title' => 'Settings', 'description' => 'Configure default and theme specific settings.', 'page callback' => 'drupal_get_form', 'page arguments' => array('system_theme_settings'), 'access arguments' => array('administer themes'), 'type' => MENU_LOCAL_TASK, 'file' => 'system.admin.inc', 'weight' => 20, );
  • 8. D8 system.routing.yml system.theme_settings: path: '/admin/appearance/settings' defaults: _form: 'DrupalsystemFormThemeSettingsForm' _title: 'Appearance settings' requirements: _permission: 'administer themes'
  • 10. Route ● A route is a path which is defined for Drupal to return some sort of content on. For example, the default front page, '/node' is a route. ● Use mm.routing.yml for defining routes
  • 11. Routes and Controllers ● The routing system is responsible for matching paths to controllers, and you define those relations in routes. You can pass on additional information to your controllers in the route. Access checking is integrated as well.
  • 12. Route - Slug entity.node.preview: path: '/node/preview/{node_preview}/{view_mode_id}' defaults: _controller: 'DrupalnodeControllerNodePreviewController::view' _title_callback: 'DrupalnodeControllerNodePreviewController::title' requirements: _node_preview_access: '{node_preview}' options: parameters: node_preview: type: 'node_preview'
  • 13. /** * Defines a controller to render a single node in preview. */ class NodePreviewController extends EntityViewController { /** * {@inheritdoc} */ public function view(EntityInterface $node_preview, $view_mode_id = 'full', $langcode = NULL) { $node_preview->preview_view_mode = $view_mode_id; $build = parent::view($node_preview, $view_mode_id); return $build; } }
  • 14. example.content: path: '/example' defaults: _controller: 'DrupalexampleControllerExampleController::content' custom_arg: 12 requirements: _permission: 'access content' // ... public function content(Request $request, $custom_arg) { // Now can use $custom_arg (which will get 12 here) and $request. }
  • 15. Routes Structure ● Path(*): /node/preview/{node_preview}/{view_mode_id} ● defaults(*) ○ _controller: DrupalnodeControllerNodePreviewController::view ○ _form: DrupalCoreFormFormInterface ○ _entity_view, _entity_form: ○ _title(optional), _title_context(optional), _title_callback(optional)
  • 16. Routes Structure ● methods(optional) ● Requirements ○ _permission, _role, _access, _entity_access, _custom_access, _format, _content_type_format ○ _module_dependencies ○ _csrf_token
  • 17. Access checking Permission requirements: _permission: 'administer content types' Role requirements: _role: 'administrator'
  • 18. Access checking - Custom class NodeRevisionAccessCheck implements AccessInterface { public function access(Route $route, AccountInterface $account, $node_revision = NULL, NodeInterface $node = NULL) { if ($node_revision) { $node = $this->nodeStorage->loadRevision($node_revision); } $operation = $route->getRequirement('_access_node_revision'); return AccessResult::allowedIf($node && $this->checkAccess($node, $account, $operation))->cachePerPermissions()->addCacheableDependency($node); } }
  • 19. Route - CSRF Protection aggregator.feed_refresh: path: '/admin/config/services/aggregator/update/{aggregator_feed}' defaults: _controller: 'DrupalaggregatorControllerAggregatorController::feedRefresh' _title: 'Update items' requirements: _permission: 'administer news feeds' _csrf_token: 'TRUE'
  • 20. Routes - Altering class NodeAdminRouteSubscriber extends RouteSubscriberBase { protected function alterRoutes(RouteCollection $collection) { if ($this->configFactory->get('node.settings')->get('use_admin_theme')) { foreach ($collection->all() as $route) { if ($route->hasOption('_node_operation_route')) { $route->setOption('_admin_route', TRUE); } } } } }
  • 22. Dynamic Routes - Cont. class ImageStyleRoutes implements ContainerInjectionInterface { public function routes() { $routes = []; $directory_path = $this->streamWrapperManager->getViaScheme('public')->getDirectoryPath(); $routes['image.style_public'] = new Route( '/' . $directory_path . '/styles/{image_style}/{scheme}', [ '_controller' => 'DrupalimageControllerImageStyleDownloadController::deliver', ], [ '_access' => 'TRUE', ] ); return $routes; } }
  • 23. Route-Parameter Upcasting entity.node.preview: path: '/node/preview/{node_preview}/{view_mode_id}' defaults: _controller: 'DrupalnodeControllerNodePreviewController::view' _title_callback: 'DrupalnodeControllerNodePreviewController::title' requirements: _node_preview_access: '{node_preview}' options: parameters: node_preview: type: 'node_preview'
  • 24. Route-Parameter Upcasting Cont. node.services.yml node_preview: class: DrupalnodeParamConverterNodePreviewConverter arguments: ['@user.private_tempstore'] tags: - { name: paramconverter } lazy: true
  • 25. Route-Parameter Upcasting Cont. class NodePreviewConverter implements ParamConverterInterface { public function convert($value, $definition, $name, array $defaults) { $store = $this->tempStoreFactory->get('node_preview'); if ($form_state = $store->get($value)) { return $form_state->getFormObject()->getEntity(); } } public function applies($definition, $name, Route $route) { if (!empty($definition['type']) && $definition['type'] == 'node_preview') { return TRUE; } return FALSE; }
  • 26. What’s for Drupal 9? ● Consider having a single class for Match Dumper, Route Provider and Route Builder ● Automatically unserialize request data and serialize outgoing data