How to Create Custom Commands in CodeIgniter

Hii, Welcome to larachamp. A website where you can browse some interesting stuff about PHP , Laravel and Codeigniter as well. Today is topic is how we can create custom commands in codeIgniter. Well, I also didn’t know about this before but today I have created a command and saw that how interesting it is.

you can use it very wisely if you are really curious about it then nothing important than this. Let’s move forward and see how we will create a custom command in codeIgniter4 and use to build some amazing stuff.

How to Create Custom Commands in CodeIgniter

How to Create Custom Command

  1. We do have commands directory under App directory. All the custom commands will be there. If you don’t have then create command and you can see the folder after that.
  2. Go to CLI and create command using command below.
php spark make:command command_name
  • You can do lot of smart things using this file now. I’ll show you an example.

How custom commands work in CodeIgniter

Now, I’ll show you how does it work. Now for example I have a user model which is representing the users table. And I need to create some test records without running query all the time or seeder may be.

Now, what we will do.

We will create a custom command using CLI.

php spark make:command CreateUser

Now we will have this file under the command directory in under App directory. Now, I will open this file and see there we would have some properties that we have to fill with information about the command.

<?php

namespace App\Commands;

use App\Models\UserModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class CreateUser extends BaseCommand
{
    /**
     * The Command's Group
     *
     * @var string
     */
    protected $group = 'CodeIgniter';

    /**
     * The Command's Name
     *
     * @var string
     */
    protected $name = 'create:user';

    /**
     * The Command's Description
     *
     * @var string
     */
    protected $description = 'create user with console command';

    /**
     * The Command's Usage
     *
     * @var string
     */
    protected $usage = 'create:user [arguments] [options]';

    /**
     * The Command's Arguments
     *
     * @var array
     */
    protected $arguments = [
    ];

    /**
     * The Command's Options
     *
     * @var array
     */
    protected $options = [
    ];

    /**
     * Actually execute a command.
     *
     * @param array $params
     */
    public function run(array $params)
    {
        $username = CLI::getSegment(2);
        if (!empty($username)) {
            $userModel = new UserModel();
            $user = $userModel->insert(['name' => 'RandomCI']);
            if ($user) {
                CLI::write('User Created Successfull', 'green', 'blue');
            }
        }
        // $this->call('create:user');
    }
}

I have created a UserModel in which I have inserted the records using command.

UserModel I have changed nothing just used name in AllowedFields ✌😁

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['name'];

    // 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    = [];
}

But this not stops here it has lot of other features also. That you browse here Codeigniter Custom Commands. The link that I have attached in this tab you will find everthing about command line usage so do not miss anything in order to use it very well.

Suggestion

You can read more about CodeIgniter On CodeIgniter Page

First time I used it today. And If you think this isn’t enough what you have read then go to vendor folder of the core CodeIgniter code. And in that at this point of time commands written at vendor\codeigniter4\framework\system\Commands\Generators\Views this path. So, You can learn from there also. How CI using commands itself. Try to contribute some interesting features if you can I am also thinking if something does matter most into there.

Thanks Again.

1 thought on “How to Create Custom Commands in CodeIgniter”

Comments are closed.