In Codeigniter, when it runs it follows a specific execution process. So, in CodeIgniter 4, we can use events to perform certain actions that we want to occur at a specific point in the execution process.
For instance, we might want to activate one of our own scripts in a different location or need to run a script either before or right after our controller’s load. These are the circumstances where the event’s concept can be used.
Enable Application Events
We had to use configuration files to enable events in earlier iterations of CodeIgniter. However, events are already enabled by default in this CodeIgniter 4 version.
Events are available everywhere and are always enabled.
An event configuration file for CodeIgniter 4 can be found at /app/Config/Events.php. In that file, we will define our events.
Event Points in CodeIgniter 4
The list of event points, or the execution breakpoints, where we can define or activate our event function, is provided below.
- pre_system Called early during system execution. At this time, only the benchmark and events classes have been loaded. There has been no routing or other process.
- post_controller_constructor called immediately following the instantiation of your controller but before any method calls are made.
- post system called at the conclusion of system execution after the finalized data is sent to the browser, along with the final rendered page.
- email triggered following a successful CodeIgniter\Email\Email transmission. receives as a parameter an array of the Email class’s properties.
- DBQuery called following a successful database query. the Query object is received.
- migrate A call to the latest() or regress is made following a successful migration (). receives the name of the method and the current properties of MigrationRunner.
Defining an Event
Either a separate file or the Events.php file found in the /app/Config directory can be created in order to create an event.
Custom events are typically defined in the Events.php file rather than in a separate file.
We must import the Events class into the file where we define events.
use CodeIgniter\Events\Events;
With event point, an event can be defined in a variety of ways. The code snippets below are what we used to define events in the file Events.php.
Method #1
When a hook point is activated, a class method is called.
Events::on('<event-point>', ['MyClass', 'MyFunction']);
Method #2
calling a standalone function when the hook point triggers
Events::on('<event-point>', 'some_function');
Method #3
calling a method from a loaded class instance when the hook point triggers
$class_obj = new AnyClass();
Events::on('<event-point>', [$class_obj, 'some_method']);
Method #4
When a hook point is activated, a class’s static method is called.
Events::on('<event-point>', 'SomeClass::someMethod');
Method #5
Use a closure function to handle hook point triggers.
Events::on('<event-point>', function(...$params) {
// logics
});
So, these are some potential approaches to defining an event in CodeIgniter 4.
Create Events - Examples
Using closure Function to Handle Event Callbacks
Open /app/Config/Events.php
Events.php
//...
Events::on("pre_system", function(){
echo "pre_system running - when application initializes";
});
Events::on("post_controller_constructor", function(){
echo "post_controller_constructor running - After Controller's constructor but before any method";
});
Events::on("post_system", function(){
echo "pre_system running - after complete page load";
});
//...
Using Class Method to Handle Event Callbacks
Create a class first. We must create a folder inside /app to build our custom class.
Make a folder called Hooks in the app directory (/app/Hooks).
Create a class file called MyClass.php inside the Hooks folder, that is, /app/Hooks/MyClass.php.
Open MyClass.php
Insert the following code into that file.
MyClass.php
<?php
class MyClass{
public function before_controller(){
echo "pre_system running - when application initializes";
}
public function after_controller_constructor(){
echo "post_controller_constructor running - After Controller's constructor but before any method";
}
public function before_method(){
echo "pre_system running - after complete page load";
}
}
This file must then be loaded into the application. We use the Autoload.php file to automatically load files.
Navigate to /app/Config/Autoload.php
Look for $classmap and insert this code there.
public $classmap = [
"MyClass" => APPPATH . 'Hooks/MyClass.php',
];
The creation of a class file and loading into the application are both successful.
The class method’s to Events callback must then be used
Open /app/Config/Events.php
Events.php
// Load Class
use MyClass;
//...
$myclass = new MyClass; // Create an instance of MyClass
// Binding class methods as event callbacks
Events::on("pre_system", [$myclass, "before_controller"]);
Events::on("post_controller_constructor", [$myclass, "after_controller_constructor"]);
Events::on("post_system", [$myclass, "before_method"]);
//...
Using Static Methods of Class To handle Event callbacks
the same procedures we used to create a class. Open that up and add a few static methods.
MyClass.php
<?php
class MyClass{
public static function before_controller(){
echo "pre_system running - when application initializes";
}
public static function after_controller_constructor(){
echo "post_controller_constructor running - After Controller's constructor but before any method";
}
public static function before_method(){
echo "pre_system running - after complete page load";
}
}
Open /app/Config/Events.php
Events.php
// Load Class
use MyClass;
//...
// Binding class static methods as event callbacks
Events::on("pre_system", "MyClass::before_controller");
Events::on("post_controller_constructor", "MyClass::after_controller_constructor");
Events::on("post_system", "MyClass::before_method");
//...
The overall process of events will go something like this.
“pre_system” callback execute initially
– Application Constructor will run
“post_controller_constructor” Before any method will execute
– Application methods will run
“post_system” After complete page, load it will run.
Events Priority Settings
Consider the case where numerous callbacks are bound to a single event point. For instance,
Events::on('post_controller_constructor', function(){ ... });
Events::on('post_controller_constructor', function(){ ... });
Events::on('post_controller_constructor', function(){ ... });
We have multiple closure functions that are called from the same event point, post controller constructor, as can be seen.
So, can we manage how these callbacks are executed?
The CodeIgniter 4 application has defined event priorities.
define('EVENT_PRIORITY_LOW', 200);
define('EVENT_PRIORITY_NORMAL', 100);
define('EVENT_PRIORITY_HIGH', 10);
So, we can manage how event callbacks are executed by passing the specified priority number.
Events::on('post_controller_constructor', function(){ ... }, 25); // Executes Second
Events::on('post_controller_constructor', function(){ ... }, 21); // Executes First
Events::on('post_controller_constructor', function(){ ... }, 33); // Executes Third
We sincerely hope that this in-depth article on CodeIgniter 4 Complete Events Tutorial was helpful to you.