Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save achraf-jeday/50a264e8ef75534bedb5bbef890fc2ec to your computer and use it in GitHub Desktop.
Save achraf-jeday/50a264e8ef75534bedb5bbef890fc2ec to your computer and use it in GitHub Desktop.
Example of overriding a route controller in Drupal 8
services:
example_module.route_subscriber:
class: Drupal\example_module\Routing\RouteSubscriber
tags:
- { name: event_subscriber }
<?php
/**
* @file
* Contains \Drupal\example_module\Controller\ExampleModuleController.
*/
// THIS FILE BELONGS AT /example_module/src/Controller/ExampleModuleController.php
namespace Drupal\example_module\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* An example controller.
*/
class ExampleModuleController extends ControllerBase {
/**
* {@inheritdoc}
*/
public function content() {
$build = array(
'#type' => 'markup',
'#markup' => t('Hello World!'),
);
return $build;
}
}
<?php
/**
* @file
* Contains \Drupal\example_module\Routing\RouteSubscriber.
*/
// THIS FILE BELONGS AT /example_module/src/Routing/RouteSubscriber.php
namespace Drupal\example_module\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
public function alterRoutes(RouteCollection $collection) {
// Replace "some.route.name" below with the actual route you want to override.
if ($route = $collection->get('some.route.name')) {
$route->setDefaults(array(
'_controller' => '\Drupal\example_module\Controller\ExampleModuleController::content',
));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment