Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By slootjes on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.7.x
Issue links:
Description:
Allow invokable services as controllers where controller implements the __invoke magic method rather than an action, popular within the ADR (Action–domain–responder) architectural pattern.
An invokable service can be any service configured with dependency injection;
# modules/contrib/invoke/src/Controller/Invoke.php
namespace Drupal\invoke\Controller;
use Symfony\Component\HttpFoundation\Response;
class InvokeController {
/**
* The database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* @param \Drupal\Core\Database\Connection $connection
* The database connection.
*/
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public function __invoke() {
// do something with database connection
return new Response('data');
}
}
# invoke.services.yml
services:
controller.invoke:
class: Drupal\invoke\Controller\InvokeController:
arguments: ['@database']
acme_invoke:
# invoke.routing.yml
invoke:
path: /invoke
defaults:
_controller: controller.invoke
requirements:
_access: 'TRUE'
or configure it by it's FQCN (fully qualified class name):
# invoke.services.yml
services:
Drupal\invoke\Controller\InvokeController:
arguments: ['@database']
acme_invoke:
# invoke.routing.yml
invoke:
path: /invoke
defaults:
_controller: Drupal\invoke\Controller\InvokeController
requirements:
_access: 'TRUE'
It could also be a FQCN of a class which is not configured by dependency injection and does not have constructor arguments:
# modules/contrib/invoke/src/Controller/Invoke.php
namespace Drupal\invoke\Controller;
use Symfony\Component\HttpFoundation\Response;
class InvokeController {
public function __invoke() {
return new Response('Hello World');
}
}
acme_invoke:
# invoke.routing.yml
invoke:
path: /invoke
defaults:
_controller: Drupal\invoke\Controller\InvokeController
requirements:
_access: 'TRUE'
Impacts:
Module developers