CodeIgniter 4.x CLI Generate Command

Table of Contents

Generate Controller Class

Format :

				
					php spark make:controller <nama-controller> [options]
				
			

Options:

  • –bare: Extends from CodeIgniter\Controller instead of BaseController.
  • –restful: Extends from a RESTful resource. Choices are controller and presenter. Defaults to controller.
  • –namespace: Set the root namespace. Defaults to value of APP_NAMESPACE.
  • –suffix: Append the component suffix to the generated class name.
  • –force: Set this flag to overwrite existing files on destination.

Sebagai contoh misalkan kita ingin generate file controller dengan nama PostController, kita run command di bawah ini.

				
					php spark make:controller PostController
				
			

Terdapat keterangan ada file baru yang berhasil dibuat, yaitu file :

  1. Controllers/PostController.php.

Selanjutnya kita coba buka file Controllers/PostController.php di text editor. Kita bisa lihat ada class controller, yaitu PostController dengan satu method default index().

				
					<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class PostController extends BaseController
{
    public function index()
    {
        //
    }
}
				
			

Pada baris kode di atas, PostController secara default extends atau merupakan class turunan dari class BaseController.

Nah, misalkan kita ingin buat class dengan tujuan yang berbeda, misalnya untuk Restful resource. Kita bisa tambahkan opsi –restful.

				
					php spark make:controller ProductController --restful
				
			

Sekarang kita coba buka file Controllers/ProductController.php di text editor.

				
					<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class ProductController extends ResourceController
{
    /**
     * Return an array of resource objects, themselves in array format
     *
     * @return mixed
     */
    public function index()
    {
        //
    }

    /**
     * Return the properties of a resource object
     *
     * @return mixed
     */
    public function show($id = null)
    {
        //
    }

    /**
     * Return a new resource object, with default properties
     *
     * @return mixed
     */
    public function new()
    {
        //
    }

    /**
     * Create a new resource object, from "posted" parameters
     *
     * @return mixed
     */
    public function create()
    {
        //
    }

    /**
     * Return the editable properties of a resource object
     *
     * @return mixed
     */
    public function edit($id = null)
    {
        //
    }

    /**
     * Add or update a model resource, from "posted" properties
     *
     * @return mixed
     */
    public function update($id = null)
    {
        //
    }

    /**
     * Delete the designated resource object from the model
     *
     * @return mixed
     */
    public function delete($id = null)
    {
        //
    }
}
				
			

Mirip seperti php artisan make:controller  ProductController –resource di Laravel

Generate Model Class

Format

				
					php spark make:model <nama-model> [options]
				
			

Options :

  • –dbgroup: Database group to use. Defaults to default.
  • –return: Set the return type from array, object, or entity. Defaults to array.
  • –table: Supply a different table name. Defaults to the pluralized class name.
  • –namespace: Set the root namespace. Defaults to value of APP_NAMESPACE.
  • –suffix: Append the component suffix to the generated class name.
  • –force: Set this flag to overwrite existing files on destination.

Sebagai contoh, kita coba buat class model baru dengan nama PostModel. Kita run command berikut ini.

				
					php spark make:model PostModel
				
			

Kita buka file hasilnya Models/PostModel.php di text editor dan kurang lebih hasil generate-nya seperti baris kode di bawah ini :

				
					<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

Format

				
					php spark make:migration <nama-class> [options]
				
			

Options :

  • –session: Generate a migration file for database sessions.
  • –table: Set the table name to use for database sessions. Defaults to ci_sessions.
  • –dbgroup: Set the database group for database sessions. Defaults to default group.
  • –namespace: Set the root namespace. Defaults to value of APP_NAMESPACE.
  • –suffix: Append the component suffix to the generated class name.
  • –force: Set this flag to overwrite existing files on destination.

Contohnya kita coba buat file migration untuk `Post` table. Kita run command berikut ini : 

				
					php spark make:migration Post
				
			

Kita buka file hasilnya app/Database/Migrations/_Post.php di text editor dan edit hasil generate-nya sbb :

				
					<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Post extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'TINYINT',
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'title' => [
                'type'       => 'VARCHAR',
                'constraint' => '50',
            ],
            'content' => [
                'type'       => 'VARCHAR',
                'constraint' => '200',
            ],
            'created_at' => [
                'type'    => 'TIMESTAMP',
                'default' => new RawSql('CURRENT_TIMESTAMP'),
            ],
            'updated_at' => [
                'type'    => 'TIMESTAMP',
                'default' => new RawSql('CURRENT_TIMESTAMP'),
            ],
            'deleted_at' => [
                'type'    => 'TIMESTAMP',
                'default' => new RawSql('CURRENT_TIMESTAMP'),
            ],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('posts');
    }

    public function down()
    {
        $this->forge->dropTable('posts');
    }
}

				
			

Untuk menabahkan table ke database sesuai file di atas jalankan perintah berikut

				
					php spark migrate
				
			

Perintah di atas akan mendeploy keseluruhan file migration yang belum pernah dijalankan

Sementara untuk menjalankan file yang dipilih perinahnya sbb :

				
					php spark make:migration Menu
				
			
Generate Seeder

Format :

				
					make:seeder <name> [options]
				
			

Options :

  • –namespace: Set the root namespace. Defaults to value of APP_NAMESPACE.
  • –suffix: Append the component suffix to the generated class name.
  • –force: Set this flag to overwrite existing files on destination.

Database seeding adalah cara sederhana untuk menambahkan data ke dalam database. Biasanya database seed ini sangat bermanfaat pada saat development, terutama saat kita perlu sample data.

Untuk generate sebuah seeder class, kita jalankan perintah sbb :

				
					php spark make:seeder PostSeeder
				
			

Selanjutnya kita coba buka file app/Database/Seeds/PostSeeder.php sbb :

				
					<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use CodeIgniter\I18n\Time;
use App\Models\Post;

class PostSeeder extends Seeder
{
    public function run()
    {
        $post = new Post;
        $faker = \Faker\Factory::create();

        for ($i = 0; $i < 100; $i++) {
            $post->save(
                [
                    'title'       =>    $faker->text,
                    'content'     =>    $faker->text,
                    'created_at'  =>    Time::createFromTimestamp($faker->unixTime()),
                    'updated_at'  =>    Time::now()
                ]
            );
        }
    }
}

				
			

Lalu jalankan perintah berikut di terminal

				
					php spark db:seed PostSeeder
				
			
Command Generate Scaffolding

Pada CodeIgniter 4 tersedia command untuk generate beberapa class sekaligus, seperti controller, model, entity, migration dan seeder dengan satu command, yaitu make:scaffold command.

Sebagai contoh di sini kita coba generate class yang berhubungan dengan objek Post, kita run command berikut ini :

				
					php spark make:scaffold Post --suffix --restful
				
			

Perintah di atas akan mengenerate beberapa class sekaligus sbb :

  1. App\Controllers\PostController.php
  2. App\Models\PostModel.php
  3. App\Database\Migrations\_PostMigration.php and
  4. App\Database\Seeds\PostSeeder.php

Note : tanpa menggunakan options –suffix semua file/class akan bernama Post.php dimana akan membuat error jika dipanggil dari class yang bernama sama tanpa menggunakan alias. Sementara –restful akan menambahkan beberapa function crud pada Controller