CodeIgniter 4 Scaffolding Generator Tutorial with Example

Share this Article
Reading Time: 9 minutes
457 Views

Scaffolding auto generates Controller, Model, Migration & Seeder file inside CodeIgniter 4 application. Click here for CodeIgniter 4 Generators. These are the newest features of CodeIgniter 4.

Inside this article we will see the concept of CodeIgniter 4 scaffolding generator. We will also consider an example to understand it in a very clear way.

How to use CodeIgniter 4 Scaffolding concept, we will see step by step concept. It will be very interesting topic in latest development version of CodeIgniter 4.

Learn More –

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.


Turn Development Mode On

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.


Create Database & Connectivity

We need to create a database. For database we will use MySQL.

CREATE DATABASE codeigniter4_app;

Next, we need to connect with application.

Database Connectivity to Application

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Generating Scaffolding in Application

This is the newest feature in CodeIgniter v4.x. Scaffolding simply means we will have a command by which we can generate a complete set of files which helps in application development.

Here, we will use the concept of php spark to generate scaffolding.

Open project into terminal and type this command. This will open the help manual guide to use make:scaffold command.

$ php spark help make:scaffold

Let’s use this command to create scaffolding files in application.

$ php spark make:scaffold Product --suffix

–suffix is used to add Component name with each class name like Controller, Model etc.

It will generate 4 different files.

  • Controller File – ProductController.php inside /app/Controllers
  • Model File – ProductModel.php inside /app/Models
  • Migration File – 2021-02-15-155935_ProductMigration.php at /app/Database/Migrations
  • Seeder File – ProductSeeder.php at /app/Database/Seeds

Scaffold – Migration Settings

Open 2021-02-15-155935_ProductMigration.php from /app/Database/Migrations folder.

Copy and paste the given code into that file.

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class ProductMigration extends Migration
{
	public function up()
	{
		$this->forge->addField([
			"id" => [
				"type" => "INT",
				"auto_increment" => true,
				"unsigned" => true,
				"constraint" => 5
			],
			"name" => [
				"type" => "VARCHAR",
				"constraint" => 50,
				"null" => false
			],
			"description" => [
				"type" => "TEXT",
				"null" => true
			],
			"cost" => [
				"type" => "INT",
				"constraint" => 5,
				"null" => false
			],
			"product_image" => [
				"type" => "VARCHAR",
				"constraint" => 150,
				"null" => true
			]
		]);

		$this->forge->addPrimaryKey("id");
		$this->forge->createTable("products");
	}

	public function down()
	{
		$this->forge->dropTable("products");
	}
}

This file contains the table structure/scheme which we will create to store data.

Migrate Migration File

Open terminal and type this command.

$ php spark migrate

It will create a products table into database.


Scaffold – Seeder Settings

Open ProductSeeder.php from /app/Database/Seeds folder.

Copy and paste the given code into that file.

<?php

namespace App\Database\Seeds;

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

class ProductSeeder extends Seeder
{
    public function run()
    {
		for($i = 0; $i < 50; $i++){
			$this->db->table("products")->insert($this->generateTestProducts());
		}
    }

    public function generateTestProducts()
    {
        $faker = Factory::create();

		return [
			"name" => $faker->sentence(2),
			"description" => $faker->sentence(10),
			"cost" => $faker->numberBetween(100, 250),
			"product_image" => $faker->imageUrl(100, 100)
		];
    }
}

This file is to seed fake data into table.

Run Seeder File to Seed Data

Open terminal and type this command.

$ php spark db:seed ProductSeeder

It will seed dummy data into database table products.


Scaffold – Model Settings

Open ProductModel.php from /app/Models folder.

Copy and paste the given code into that file.

<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'products';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [ 
      "name", 
      "description", 
      "cost", 
      "product_image" 
    ];

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

This model file is for communication with products table.


Scaffold – Controller Settings

Open ProductController.php from /app/Controllers folder.

Copy and paste the given code into that file.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;

class ProductController extends BaseController
{
    public function index()
    {
        $product_obj = new ProductModel();

		// Select all products from table	
        $products = $product_obj->findAll();

		// Send this product variable to any view file
		// ...
    }

    public function insertProduct()
    {
		$product_obj = new ProductModel();
		
		// Insert product row into table
		$product_obj->insert([
			"name" => "New Product",
			"description" => "Product Sample description",
			"cost" => 120,
			"product_image" => "https://product-thumbnail-url.com"
		]);
	}
	
	public function updateProduct(){
		$product_obj = new ProductModel();

		$product_id = 5; // ID to update

		// Update product information by product id
		$product_obj->update($product_id, [
			"name" => "Update Product",
			"description" => "Product Sample description update",
			"cost" => 50,
			"product_image" => "https://product-thumbnail-url.com"
		]);
	}

	public function deleteProduct(){
		$product_obj = new ProductModel();

		$product_id = 5; // ID to delete

		// Delete product by ID
		$product_obj->delete($product_id);
	}
}

Inside this controller file –

  • index() Method – List all data from products table by Model.
  • insertProduct() Method – Insert data into products table by Model
  • updateProduct() Method – Update data to products table using id by Model
  • deleteProduct() Method – Delete data using id by Model

Routes Configurations

Let’s configure routes for methods of Controller.

Open Routes.php from /app/Config

//...

$routes->group("product", function($routes){

	// Call - <url>/product
	$routes->get("/", "ProductController::index");
	// Call - <url>/product/add-product
	$routes->get("add-product", "ProductController::insertProduct");
	// Call - <url>/product/update-product
	$routes->get("update-product", "ProductController::updateProduct");
	// Call - <url>/product/delete-product
	$routes->get("delete-product", "ProductController::deleteProduct");
});

Application Testing

Start development server:

$ php spark serve

Open browser and type these URLs –

  • List data – http://localhost:8080/product
  • Insert data – http://localhost:8080/product/add-product
  • Update data – http://localhost:8080/product/update-product
  • Delete data – http://localhost:8080/product/delete-product

We hope this article helped you to learn CodeIgniter 4 Scaffolding Generator Tutorial with Example 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

Leave a Comment