CodeIgniter’s Events feature provides a means to tap into and modify the inner workings of the framework without hacking core files.
When CodeIgniter runs it follows a specific execution process. So when we want to cause some action to take place at a particular stage in the execution process, we can do using events in CodeIgniter 4.
For example, we might want to run a script right before our controllers get loaded, or right after, or we might want to trigger one of own own scripts in some other location. So these are the cases where we can use events concept.
Learn More –
- Bootstrap Growl jQuery Notification to CodeIgniter 4
- Call MySQL Stored Procedure in CodeIgniter 4 Tutorial
- Change Default Timezone in CodeIgniter 4 Tutorial
- CodeIgniter 4 Command – Change PHP Spark Default PORT
Inside this article we will see CodeIgniter 4 Complete Events. Let’s get started.
CodeIgniter 4 Installation
To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.
composer create-project codeigniter4/appstarter codeigniter-4
Assuming you have successfully installed application into your local system.
Environment (.env) Setup
When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env
Either we can do via renaming file as simple as that. Also we can do by terminal command.
Open project in terminal
cp env .env
Above command will create a copy of env file to .env file. Now we are ready to use environment variables.
Enable Development Mode
CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.
Open .env file from root.
# CI_ENVIRONMENT = production
// Do it to
CI_ENVIRONMENT = development
Now application is in development mode.
Enable Application Events
In previous versions of CodeIgniter, we need to enable by configuration files. But in this CodeIgniter 4 version, already events by default enabled.
Events are always enabled, and are available globally.
In CodeIgniter 4, event configuration file we can find at /app/Config/Events.php. We will define our events in that file.
Event Points in CodeIgniter 4
Here, is the list of event points or we can say the execution breakpoints where we can define or trigger our event function.
- pre_system Called very early during system execution. Only the benchmark and events class have been loaded at this point. No routing or other processes have happened.
- post_controller_constructor Called immediately after your controller is instantiated, but prior to any method calls happening.
- post_system Called after the final rendered page is sent to the browser, at the end of system execution after the finalised data is sent to the browser.
- email Called after an email sent successfully from
CodeIgniter\Email\Email
. Receives an array of theEmail
class’s properties as a parameter. - DBQuery Called after a successfully-completed database query. Receives the
Query
object. - migrate Called after a successful migration call to
latest()
orregress()
. Receives the current properties ofMigrationRunner
as well as the name of the method.
Inside this article of event tutorial we will implement and see the event points – pre_system, post_controller_constructor, post_system into action.
Defining an Event
To create an event either we can create a separate file or we can do within Events.php file of /app/Config.
In most cases, custom events defined in Events.php file instead of creating a new file for it.
When we define events in separate file, we need to import Events class there.
use CodeIgniter\Events\Events;
There are several different ways to define an event with event point. These are the code snippets we have taken to define events into same file Events.php
Method #1
When hook point triggers, calling a method from a class.
Events::on('<event-point>', ['MyClass', 'MyFunction']);
Method #2
When hook point triggers, calling a standalone function.
Events::on('<event-point>', 'some_function');
Method #3
When hook point triggers, calling method by instance of loaded class.
$class_obj = new AnyClass();
Events::on('<event-point>', [$class_obj, 'some_method']);
Method #4
When hook point triggers, calling a static method from a class.
Events::on('<event-point>', 'SomeClass::someMethod');
Method #5
When hook point triggers, handling using a closure function.
Events::on('<event-point>', function(...$params) {
// logics
});
So, these are the possible ways by the help of which we can define an event inside CodeIgniter 4.
Create Events – Examples
Using closure Function to Handle Event Callbacks
Open /app/Config/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
Let’s create a class. To store our custom class we need to create a folder inside /app.
- Create a Folder with name Hooks inside /app i.e /app/Hooks
- Create a class file with name MyClass.php (you can choose any name) inside Hooks folder i.e /app/Hooks/MyClass.php
Open MyClass.php
Add this given code into that file.
<?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"; } }
Next, we need to load this file into application. For autloading files we use Autoload.php file.
Open /app/Config/Autoload.php
Search for $classmap and add this piece of code into it.
public $classmap = [
"MyClass" => APPPATH . 'Hooks/MyClass.php',
];
Successfully, we have all basic things like creating a class file and loading into application.
Next, we need to use the class method’s to Events callback.
Open /app/Config/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
Same steps we have for creating a class. Let’s open that and add few static methods into it.
<?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
// 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
Let’s say we have many callbacks bind with a single event point. For example
Events::on('post_controller_constructor', function(){ … });
Events::on('post_controller_constructor', function(){ … });
Events::on('post_controller_constructor', function(){ … });
As we can see, we have multi closure functions called with same event point post_controller_constructor
So, can we control the process of execution of these callbacks?
We have event priorities defined in CodeIgniter 4 application.
define('EVENT_PRIORITY_LOW', 200);
define('EVENT_PRIORITY_NORMAL', 100);
define('EVENT_PRIORITY_HIGH', 10);
So, by passing the given priority number … we can control the process of execution of event callbacks.
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 hope this article helped you about – CodeIgniter 4 Complete Events Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.