Upgrade Controllers
Documentations
What has been changed
Since namespaces have been added to CodeIgniter 4, the controllers must be changed to support namespaces.
The constructor of CI4 Controller does not automatically load core classes into the properties.
CI4’s Controller has a special constructor initController().
CI4 provides Request and Responses objects for you to work with - more powerful than the CI3-way.
If you want a base controller (
MY_Controller
in CI3), use app/Controllers/BaseController.php.Calling
echo
within Controllers, as in CI3, is still supported, but it is recommended that a string or Response object be returned from Controllers.
Upgrade Guide
First, move all controller files to the folder app/Controllers.
Add this line just after the opening php tag:
namespace App\Controllers;
Replace
extends CI_Controller
withextends BaseController
.Remove the line
defined('BASEPATH') OR exit('No direct script access allowed');
if it exists.
namespace App\Controllers\Users\Auth;
and the controller path in the version 4
should look like this: app/Controllers/Users/Auth/Register.php. Make sure to have the first letters of
the sub-directories as capitalized.use
statement below the namespace definition in order to extend the BaseController
:
use App\Controllers\BaseController;
Code Example
CodeIgniter Version 3.x
Path: application/controllers:
<?php
class Helloworld extends CI_Controller
{
public function index($name)
{
echo 'Hello ' . html_escape($name) . '!';
}
}
CodeIgniter Version 4.x
Path: app/Controllers:
<?php
namespace App\Controllers;
class Helloworld extends BaseController
{
public function index($name)
{
return 'Hello ' . esc($name) . '!';
}
}