CI 4 What are Routes?

In any application, routes are the rules which maps the functions with URL and control application re-directions. Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method.

https://example.com/class/method/parameter

CodeIgniter 4 Route Basics

In CodeIgniter 4, routes configured into Routes.php file which is inside /app/Config folder.

By default you can find a route which is available when you install a codeigniter 4 setup.

$routes->get('/', 'Home::index');

$routes is an instance of the RouteCollection class. A route simply takes the URI on the left, and maps it to the controller and method on the right, along with any parameters that should be passed to the controller. 

  • / It’s a URL
  • Home It is a controller class
  • index Method of Home Controller class
  • get() Method from RouteCollection class, which is GET request type

RouteCollection class provide several methods according to HTTP request type like – POST, GET, DELETE etc.

In CodeIgniter 4 application, creating routes includes method type. We can use following methods like $routes->get()$routes->post()$routes->match()$routes->add() etc.

//...

// Using add() method
$routes->add("about-us", "Site::aboutUs");
$routes->add("products", "Site::ourProducts");
$routes->add("services/(:num)", "Site::services/$1");

// Using get() method
$routes->get("about-us", "Site::aboutUs");
$routes->get("products", "Site::ourProducts");
$routes->get("services/(:num)", "Site::services/$1");

//...

Inside these routes, we need to create and process request by using controller’s method.

CodeIgniter 4 Route Closures

When we define route closures, it means we are going to call request function in route file itself. Have a look,

//...

// route with static message
$routes->get("contact-us", function () {

    echo "<h1>Welcome to Online Web Tutor</h1>";
});

// route with view file
$routes->get("about-us", function () {

    return view("about-us"); // /app/Views/about-us.php
});

// route with parameter
$routes->get("services/(:num)", function ($id) {

    echo "ID: ".$id;
});

//...

We can define following types of routes in codeigniter 4 application –

  • Named route
  • Parametrized route
  • Closure route
  • Route redirection
  • Route group

We will see about each in upcoming sessions.