SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
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!

Más contenido relacionado

La actualidad más candente

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 DeveloperGary 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 Browserifycrgwbr
 
Your first d8 module
Your first d8 moduleYour first d8 module
Your first d8 moduletedbow
 
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 baseRobert 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 8Vladimir Roudakov
 
livedoor blogのsorryサーバの話 #study2study
livedoor blogのsorryサーバの話 #study2studylivedoor blogのsorryサーバの話 #study2study
livedoor blogのsorryサーバの話 #study2studySATOSHI 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 HTMLKei Shiratsuchi
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVCAcquisio
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
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 DevelopmentAcquia
 
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 knowkatbailey
 
Angular JS Routing
Angular JS RoutingAngular JS Routing
Angular JS Routingkennystoltz
 
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 FrontendAcquia
 

La actualidad más candente (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
 

Destacado

Google summer of code with drupal
Google summer of code with drupalGoogle summer of code with drupal
Google summer of code with drupalNaveen 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 HyderabadNaveen Valecha
 
Tercera Trobada #Xatac5a Tarragona
Tercera Trobada #Xatac5a TarragonaTercera Trobada #Xatac5a Tarragona
Tercera Trobada #Xatac5a TarragonaNeus 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 bacteriaRohit 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 FutureBronwyn Barry
 
Biases in military history
Biases in military historyBiases in military history
Biases in military historyAgha 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 screamMario 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 JavaFXsascha_klein
 
Alejandro Fernandez vs Luis Miguel
Alejandro Fernandez vs Luis MiguelAlejandro Fernandez vs Luis Miguel
Alejandro Fernandez vs Luis MiguelSusana Gallardo
 
マイクロソフトが創る未来 医療編 20170401
マイクロソフトが創る未来 医療編 20170401マイクロソフトが創る未来 医療編 20170401
マイクロソフトが創る未来 医療編 20170401Aya Tokura
 
Elixir-Conf-Japan-2017-session-ohr486
Elixir-Conf-Japan-2017-session-ohr486Elixir-Conf-Japan-2017-session-ohr486
Elixir-Conf-Japan-2017-session-ohr486Tsunenori 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 RetailNVIDIA
 
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 & HubSpotHubSpot
 

Destacado (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 a 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 Stacknuppla
 
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
 
Advanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareAdvanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareOpevel
 
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 startedSté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.jsJessie 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 7Phase2
 
Zend Framework Foundations
Zend Framework FoundationsZend Framework Foundations
Zend Framework FoundationsChuck 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
 
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 presentationMatus Szabo
 
Zend Framework 2 - Basic Components
Zend Framework 2  - Basic ComponentsZend Framework 2  - Basic Components
Zend Framework 2 - Basic ComponentsMateusz Tymek
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal DevelopmentJeff Eaton
 

Similar a 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
 

Último

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Último (20)

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

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