Page 2: Routing and Controller

2. Routing and Controller

CodeIgniter follows the MVC pattern, and all user requests are passed to the appropriate Controller via routing.

2.1. Routing Configuration (app/Config/Routes.php)

You connect URLs to Controllers in the app/Config/Routes.php file. By default, CodeIgniter routes automatically based on URL segments.

// Routes.php Example: Connect '/hello' request to Home::index
$routes->get('hello', 'Home::index');

// Default route configuration (Root URL)
$routes->get('/', 'Home::index');

2.2. Creating a Controller and Processing Requests

Create a new Controller file (e.g., app/Controllers/Products.php) and define methods that respond to user requests.

// app/Controllers/Products.php
namespace App\Controllers;

class Products extends BaseController
{
    public function list()
    {
        // Logic to retrieve product list (using Model in the next step)
        return view('product_list'); 
    }
}

Now, accessing the URL /products/list will execute the Products::list() method.