Working with CodeIgniter 4 Model and Entity

Share this Article

CodeIgniter is one of most popular framework in PHP which followed for web application development. Here, we have a article which demonstrates about working with database in CodeIgniter 4. If you go to learn there, then you can find about models introduction and usage in CodeIgniter 4 application.

Also if you are looking for Connecting Multiple databases with CodeIgniter 4, you can click and go with the informative content here.

Inside this article we will see about the concept of CodeIgniter 4 Model and Entity. One more time we will cover CodeIgniter 4 Model, CodeIgniter 4 Entity and their working principles.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Also if you want to remove public & index.php from URL – Remove Public & Index.php from CodeIgniter 4 URLs.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Working with CodeIgniter 4 Models

Models in CodeIgniter 4 are created inside /app/Models. Let’s create a model to understand the things.

Creating a file UserModel.php at /app/Models folder.

$ php spark make:model User --suffix

Open UserModel.php and write this following code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_users';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"name",
		"email",
		"phone_no"
	];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

These are the default member variables, we need to set while defining any Model. In few minutes we will start Entity lesson, then we will see that how can work with returnType value. Right now it is array.

How to Load Model to Controller ?

To Load model in any controller we have to simply import that model class into Controller file and then needs to create an instance to use that.

To understand in a clear way, Let’s create a controller file and load into it. Controllers are created inside /app/Controllers.

$ php spark make:controller User

Source code of /app/Controllers/User.php

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class User extends BaseController
{
    public function index()
    {
        $userModel = new UserModel();

        //...
    }
}

As, we can see inside this controller file. We have loaded UserModel by
use App\Models\UserModel;

Then to use it, we have created an instance $userModel = new UserModel();

By the help of CodeIgniter 4 Models, we can use it’s all provided methods for basic CRUD operations. Here, you can find a good tutorial over this CRUD Operations in CodeIgniter 4.

Now, in case if we don’t want to use the default provided insert(), save(), update() & delete() methods. Instead we want to use it in different way.

Here, we are creating some CRUD methods inside Model class.

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'tbl_users';
    // .. other member variables
    private $db;

    public function __construct()
    {
        parent::__construct();
        $this->db = \Config\Database::connect();
        // OR $this->db = db_connect();
    }

    public function insert_data($data = array())
    {
        $this->db->table($this->table)->insert($data);
        return $this->db->insertID();
    }

    public function update_data($id, $data = array())
    {
        $this->db->table($this->table)->update($data, array(
            "id" => $id,
        ));
        return $this->db->affectedRows();
    }

    public function delete_data($id)
    {
        return $this->db->table($this->table)->delete(array(
            "id" => $id,
        ));
    }

    public function get_all_data()
    {
        $query = $this->db->query('select * from ' . $this->table);
        return $query->getResult();
    }
}

As, you can see we have defined custom methods at Model to handle all database operations like for add, update, delete etc.

Next,

To call any of the Model’s method inside controller file. We can call in the same way what we did for inbuilt methods of model.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class User extends BaseController
{
    public function index()
    {
        $userModel = new UserModel();

        // Add operation
        $userModel->insert_data(array(
            "name" => "Sanjay",
            "email" => "sanjay@gmail.com",
            "phone_no" => "1234567890",
        ));

        // Update Operation
        $userModel->update_data(1, array(
            "name" => "Sanjay",
            "email" => "sanjay@gmail.com",
            "phone_no" => "1234567890",
        ));

        //...
    }
}

Let’s get started with CodeIgniter 4 Entity.


Working with CodeIgniter 4 Entity

An Entity class is a class which indicates a single database row. Entity class and it’s properties represents the database columns.

To store Entity classes, we put into /app/Entities.

By default it may be present into the directory structure. Else if not, no issues at all. Whenever we create any entity via spark command. Automatically, folder will be created.

Creating an Entity like /app/Entities/EntityName.php

$ php spark make:entity User

Open User.php from /app/Entities

<?php

namespace App\Entities;

use CodeIgniter\Entity;

class User extends Entity
{
	protected $datamap = [];
	protected $dates   = [
		'created_at',
		'updated_at',
		'deleted_at',
	];
	protected $casts   = [];
}

Let’s use the concept of Model & Entity both for inserting data into Database table.

Configure Model to use Entity

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'tbl_users';
    protected $primaryKey = 'id';
    // .. other member variables
  
    protected $returnType = 'App\Entities\User'; // configure entity to use
  
    protected $allowedFields = ['name', 'email', 'phone_no'];
}

Insert/Select Data Using Model & Entity

Loading Model & Entity classes to Controller file.

use App\Models\UserModel;
use App\Entities\User;

To insert data into table –

$userModel = new UserModel(); //Object of Model class

$user = new User(); // Object of Entity class

// First method

$data = [
	"name" => "Sanjay",
	"email" => "sanjay@gmail.com",
	"phone_no" => "1234567890",
];

$user->fill($data);

$userModel->save($user);

// Second Method
$userModel = new UserModel(); //model

$user = new User();

$user->name = "User101";
$user->email = "user101@gmail.com";
$user->phone_no = "896543133";

$userModel->save($user);

This is all about for Data Insert.

If we look for data selection, then Entity object will be returned.

$userModel = new UserModel(); //Object of Model class

$users = $userModel->findAll();

// this will return all data into User Entity object, 
// because we have configured Entity in returnType in model class

CodeIgniter 4 Entity – Data Map

As we have taken the case in which table columns are name, email and phone_no. In some cases if we want to insert data with the other names but also keep the original column names as it is. So, how can we do this ?

Configure Entity for Data Map

<?php

namespace App\Entities;

use CodeIgniter\Entity;

class User extends Entity
{
    protected $datamap = [
        "fullname" => "name",
        "emailAddress" => "email",
        "phoneNumber" => "phone_no",
    ];
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
    ];
    protected $casts = [];
}

We can use fullname in place of name, emailAddress in place of email etc. These are data map column names. Keeping original behind the screen and using their mapped column names.

Have a look the insert method –

$userModel = new UserModel(); //model

$user = new User();

$user->fullname = "User101";
$user->emailAddress = "user101@gmail.com";
$user->phoneNumber = "896543133";

$userModel->save($user);

It will work same what we have done with the original column names. Also while selecting data inside loop we can use these mapped column names to print value.

For all database related operations f we have mapped column names then we can use with no issues.


Accessors & Mutators in CodeIgniter 4 Entity

Accessors and Mutators are those features which manipulate data before saving and accessing data. Simply they provide a intermediate state where we change the value. Inside this point of discussion we will see about each of these concept in detail.

Mutators in Entity

Let’s say we have a column of password in database table. We are inserting value of password from Controller. Now, we want to make the plain text password into a hashed password from the Entity concept.

So basically when we insert value for password field, then at intermediate state of password mutator will change the value and convert into hashed value.

Let’s configure Entity for Mutator –

<?php

namespace App\Entities;

use CodeIgniter\Entity;

class User extends Entity
{
    //.. other settings
  
    // encrypting password and re-assign to password field
    function setPassword(string $password)
    {
        $this->attributes["password"] = password_hash($password, PASSWORD_BCRYPT);
        return $this;
    } 
}

Before making any mutator keep in mind these things –

  • Method name should use set keyword, Also the other name should be the column name. So here, setPassword() password is the column name.
  • After chaging value or anything we need to set value again into attributes like what we did above. $this->attributes[“password”]. password is the column name.

And at the code of saving we don’t have to do anything. It remains unchanged. As you can see here.

$userModel = new UserModel(); //model

$user = new User();

$user->name = "User101";
$user->email = "user101@gmail.com";
$user->phone_no = "896543133";
$user->password = "secret123"; 
// automatically before insertion to database, this will be in hashed format.

$userModel->save($user);

Accessors in Entity

This is other face of Entity which manipulates value before getting outputted to screen. Suppose, we have many data rows in tbl_users table. We have written query to get all data. We are using Looping statements to print value. Before print value we want to change or do something with the data, then we can easily with accessors concept.

Let’s configure Entity for Accessors –

<?php

namespace App\Entities;

use CodeIgniter\Entity;

class User extends Entity
{
    // .. other settings
  
    public function getEmail(){
        // accessor which changes the case of email address, means in upper case
        return strtoupper($this->attributes['email']);
    }

    public function getName(){
        // accessor which replaces space with _ in name value
        return str_replace(" ", "_", $this->attributes['name']);
    }
}

How to use these ?

This concept is automatically used when we print any value for email and name because accessors is created for those only.

$userModel = new UserModel();

$users = $userModel->findAll();

foreach ($users as $index => $user) {
  // before printing value, it uses accessor behind the scene
  echo $user->name . " , " . $user->email . "<br/><br/>";
}

Before making any accessor in entity, keep in mind these things –

  • We need to use get keyword in front of method name. Then we need to include the method name as column name. In getEmail(), email is the column name of table.
  • After changing or doing anything with the value, next we need to return that value.

Create Virtual Properties in Entity

Virtual field means the field which has been created only to use, they don’t really exists.

<?php

namespace App\Entities;

use CodeIgniter\Entity;

class User extends Entity
{
    // ... other settings
    // full_data is the virtual property, we can use inside application
    // This method is printing the combine value for name and email
    public function full_data(){
        return $this->attributes['name']. " ".$this->attributes['email'];
    }
}

Here, as you can see we have created a method inside Entity name full_data(). The full_data we can use it as a virtual property. Hold for a second and see.

How to use in application ?

$userModel = new UserModel();

$users = $userModel->findAll();

foreach ($users as $index => $user) {
  
  echo $user->full_data();
}

We hope this article helped you to learn about CodeIgniter 4 Model and Entity in a very detailed way.

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.

Find More on CodeIgniter 4 here

3 thoughts on “Working with CodeIgniter 4 Model and Entity”

  1. Write very good.
    I have an another question. How to use codeigniter 4 model to query like “asia%” with MySQL database.
    Thanks!

    Reply
  2. Right here is the perfect website for everyone who wants to understand this topic.
    You realize a whole lot its almost hard to argue with you
    (not that I personally will need to…HaHa). You definitely put a fresh
    spin on a subject that’s been discussed for ages.
    Excellent stuff, just great!

    Reply

Leave a Comment