H-129, Palri, Hodal, Palwal, HR
+91 9992755268

How to get a Controller and Method Name in Codeigniter 4

codeigniter 4

Get a Controller and Method Name in Codeigniter 4: As we Know Codeigniter 4 is recently launched and we have a lack of blogs and Tutorials on its. So, I am here to help you out to get the model name and controller name using routes services.

If you want to implement conditional code based on the class or method, you need to get the current class and method name in CodeIgniter. Using the Router Class in CodeIgniter, you can easily get the current controller and method name. The Router class helps to parses URIs and determines to route. The $router->controllerName() and $router-> methodName() method of Router class can be used to read them class and method property in CodeIgniter.

You can Also Read Php Function and methods.

get a Controller and Method Name in Codeigniter 4
get a Controller and Method Name in Codeigniter 4

Get or Fetch Controller Name in Codeigniter 4

For the Controller name, You need to call router service. Then, you will use controllerName() function.

$router = service('router'); 
$controller  = $router->controllerName();  

Get or Fetch Method Name in Codeigniter 4

For the Method name, You also need to call router service. Then, you will use the methodName() function.

$router = service('router');
$method = $router->methodName();

Summary of Codeigniter 4 Routes Service to getting Method or Controller name

All of the core classes within CodeIgniter are provided as “services”. This simply means that, instead of hard-coding a class name to load, the classes to call are defined within a very simple.

$logger = service('logger');
$routes = service('routes');

Also, Read How to change Codeigniter 4 Environment Variable and How PHP is Better than Other Languages.

Leave a reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.