Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Controllers

A controller is a class whose methods answer requests. The route decides which method to call, and the method returns the response: text, a page or a redirect. Controllers live in the app/Controllers folder, one class per file.

Creating a controller

php spark make:controller Posts

The command creates the file app/Controllers/Posts.php with an empty index() method. Fill it in:

// app/Controllers/Posts.php
namespace App\Controllers;
 
class Posts extends BaseController
{
    public function index(): string
    {
        return 'List of posts';
    }
}

The file name matches the class name, capital letter included. On its own the controller does not open in the browser yet — it needs a route.

Connecting a route

// app/Config/Routes.php
$routes->get('posts', 'Posts::index');

Open http://localhost:8080/posts and the line "List of posts" appears. Posts::index means "class Posts, method index".

A parameter from the address

A value from the address arrives in the method as an argument. Add a route and a method:

// app/Config/Routes.php
$routes->get('posts/(:num)', 'Posts::show/$1', ['as' => 'posts.show']);
// app/Controllers/Posts.php
public function show(int $id): string
{
    return "Post #$id";
}

The address /posts/5 prints "Post #5".

Page not found

If the requested record does not exist, the controller throws an exception and the visitor sees a page with the 404 code:

use CodeIgniter\Exceptions\PageNotFoundException;
 
public function show(int $id): string
{
    if ($id > 100) {
        throw PageNotFoundException::forPageNotFound('Post not found');
    }
 
    return "Post #$id";
}

The use line goes at the top of the file, after namespace.

BaseController

Every controller extends the BaseController class from app/Controllers/BaseController.php. From it each controller gets ready-made properties:

PropertyWhat it is
$this->requestThe current request: form data, address parameters
$this->responseThe response: headers, status code, JSON
$this->helpersThe list of helpers loaded automatically

BaseController is a good place for code shared by all pages.

Common mistake

Creating a controller is not enough: without a line in app/Config/Routes.php the address returns 404. Automatic lookup of a controller by address is off by default in CodeIgniter 4. Run php spark routes to check that the address is in the list and that the controller method is declared public.

Thanks for reading!

Donate to the site — we work hard for you.