A route is a way for Drupal to determine which system should be responsible for returning content to a request. For example, when it receives a request for /node, Drupal is able to match this to the home page and return the current list of content. Routes are defined in the {module}.routing.yml file inside the module directory. At its most basic, that file looks like:
mastering_drupal_8.test_page:
path: 'mastering_drupal_8/test'
defaults:
_controller:
'\Drupal\mastering_drupal_8\Controller\TestPageController::test'
requirements:
_permission: 'access content'
You have a name for the route, namespaced by the module that contains it. Within the route, other required elements are: path, the URL for the route; defaults, the default properties of the route; and requirements, the conditions that must be fulfilled to grant access to the route.
The most common element in defaults is the controller, which provides a callable string, typically in the format class::function. A basic controller for that route would look like:
class TestPageController extends ControllerBase {
/**
* Test.
*
* @return string
* Return Test string.
*/
public function test() {
return [
'#type' => 'markup',
'#markup' => $this->t("Test")
];
}
}
The controller extends ControllerBase and has a public function that matches the function in the routing file that returns a renderable array. The function can also return the Symfony\Component\HttpFoundation\Response object. Response objects will be sent directly and no theming or blocks will be added.