Concept of Trait in CodeIgniter 4 Tutorial with Example

Reading Time: 7 minutes
8,055 Views

In general, Traits are nothing but a reusable collection of methods and functions that can be incorporated in any other classes.

Inside this article we will see the concept of Trait in CodeIgniter 4 with Example. How to create & use it in CodeIgniter 4 application, all basic things we will cover in this trait tutorial of CodeIgniter 4.

What we will do inside this article –

  • Create a Trait in CodeIgniter i.e reusable block of code, which we can access in any controller and use it.

Learn More –

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.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Tables

Successfully, we have created a database.

Next, we need to create few tables inside database.

CREATE TABLE users (
     id int(5) unsigned NOT NULL AUTO_INCREMENT,
     name varchar(100) NOT NULL,
     email varchar(100) NOT NULL,
     updated_at datetime DEFAULT NULL,
     created_at datetime DEFAULT CURRENT_TIMESTAMP,
     PRIMARY KEY (id),
     UNIQUE KEY email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE products (
     id int(5) unsigned NOT NULL AUTO_INCREMENT,
     name varchar(100) NOT NULL,
     description text,
     amount int(5) unsigned NOT NULL,
     status int(5) NOT NULL DEFAULT '1',
     updated_at datetime DEFAULT NULL,
     created_at datetime DEFAULT CURRENT_TIMESTAMP,
     PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.


Create Seeders

In CodeIgniter 4, we have php spark commands available to work with seeders, migrations etc. Seeders are the php files which help us to create test data or fake data into tables and manage that.

Open codeigniter 4 application into terminal and type these commands.

$ php spark make:seeder User --suffix

$ php spark make:seeder Product --suffix

When we create seeder file, it will be stored inside /app/Database/Seeds folder.

Files created for seeders as –

  • UserSeeder.php for users table
  • ProductSeeder.php for products table

Seeder File: UserSeeder.php

Write the following code into it.

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use Faker\Factory;

class UserSeeder extends Seeder
{
    public function run()
    {
        for ($i = 0; $i < 10; $i++) { 
			//to add 10 users. Change limit as desired
            $this->db->table('users')->insert($this->generateUsers());
        }
    }

    private function generateUsers(): array
    {
        $faker = Factory::create();
        return [
            'name' => $faker->name(),
            'email' => $faker->email
        ];
    }
}

Seeder File: ProductSeeder.php

Write the following code into it.

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use Faker\Factory;

class ProductSeeder extends Seeder
{
    public function run()
    {
        for ($i = 0; $i < 10; $i++) { 
			//to add 10 products. Change limit as desired
            $this->db->table('products')->insert($this->generateProducts());
        }
    }

    private function generateProducts(): array
    {
        $faker = Factory::create();
        return [
            'name' => $faker->name,
			'description' => $faker->sentence(6),
			'amount' => $faker->numberBetween(50, 200),
			'status' => $faker->randomElement([1, 0])
        ];
    }
}

Successfully, we have created and updated seeder files. Faker library is a default package included in CodeIgniter 4. Here we are using faker library to generate fake data.


Seed data into database table

Run these spark commands to seed data into respective tables.

$ php spark db:seed UserSeeder

$ php spark db:seed ProductSeeder

These two commands will seed data into users table and products table.


Create Models

Open project into terminal and run this spark command.

$ php spark db:seed UserSeeder

$ php spark db:seed ProductSeeder

It will create files with name StudentModel.php & ProductModel.php at /app/Models folder.


Create Traits in CodeIgniter

There is no specific location to store trait files. Create Traits folder in /app, then create DataTrait.php file at /app/Traits file.

Open DataTrait.php and write this code into it.

<?php

namespace App\Traits;

trait DataTrait
{
    public function getData($model)
    {
        // Fetch all the data according to model
        return $model->findAll();
    }
}

Here, we have created a simple trait method, which returns all data on the basis of model what we will pass into it.


Create Routes

Open Routes.php from /app/Config folder.

//...

$routes->get("list-products", "DataController::listProducts");
$routes->get("list-users", "DataController::listUsers");

//...

Create Controller

To create controller, run this artisan command.

$ php spark make:controller Data --suffix

It will create a file with name DataController.php at /app/Controllers folder.

Open DataController.php and write this code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Traits\DataTrait;

use App\Models\ProductModel;
use App\Models\UserModel;

class DataController extends BaseController
{
    use DataTrait;

    public function listProducts()
    {
        // Get data using Trait method
        $products = $this->getData(new ProductModel());

        echo "<pre>";
        print_r($products);
    }

    public function listUsers()
    {
        // Get data using Trait method
        $users = $this->getData(new UserModel());

        echo "<pre>";
        print_r($users);
    }
}

As we can see, Single Trait method is now used to methods. even we can use the sample in any controller where we want data.


Application Testing

Open project terminal and start development server via command:

php spark serve

Product URL – http://localhost:8080/list-products

User URL – http://localhost:8080/list-users

Here, we are only displaying all data into raw format. If you want then you can show it into view file as well.

We hope this article helped you to learn about Concept of Trait in CodeIgniter 4 Tutorial with Example 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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more