Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add Getting Routing Information #9129

Merged
12 changes: 12 additions & 0 deletions user_guide_src/source/incoming/routing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@ a simple view:

.. literalinclude:: routing/020.php

Retrieving the Controller and Method Names
------------------------------------------

In some cases, you might need to determine which controller and method have been triggered by the current HTTP request.
This can be useful for logging, debugging, or conditional logic based on the active controller method.

CodeIgniter 4 provides a simple way to access the current route's controller and method names using the ``Services::router()`` class. Here is an example:
datamweb marked this conversation as resolved.
Show resolved Hide resolved

.. literalinclude:: routing/071.php

This functionality is particularly useful when you need to dynamically interact with your controller or log which method is handling a particular request.

Specifying Route Paths
======================

Expand Down
15 changes: 15 additions & 0 deletions user_guide_src/source/incoming/routing/071.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

use Config\Services;

// Get the router instance
$router = Services::router();
datamweb marked this conversation as resolved.
Show resolved Hide resolved

// Retrieve the fully qualified class name of the controller handling the current request.
$controller = $router->controllerName();

// Retrieve the method name being executed in the controller for the current request.
$method = $router->methodName();

echo 'Current Controller: ' . $controller . '<br>';
echo 'Current Method: ' . $method;