CodeIgniter 4 How To Work with Spark CLI Tutorial

Reading Time: 17 minutes
14,068 Views

Inside this article we will see the concept i.e CodeIgniter 4 How To Work with Spark CLI Tutorial. CodeIgniter 4 have many features. In the list of features a special section added called spark. Spark is a command line tool of codeigniter 4. This is newly added feature.

CodeIgniter 4 is totally updated from it’s previous versions. Multiple updates like like from directory structure to creating classes for model, controllers, routes etc.

CodeIgniter 4 Spark CLI is a command line interface which works to manage application. We will see the complete details in few seconds. This tutorial is going to be more and more interesting to get the new thing in codeigniter.

Inside this article we have covered the available commands upto CodeIgniter v4.0.3. Rest you will find more in upcoming versions.

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.

What is Spark in CodeIgniter 4?

Spark is a CodeIgniter CLI Tool. This tool have some commands which we can use and manage CodeIgniter 4 application. This features is available from latest development version 4.x.

By using Spark CLI, we can start development server of application. First we need to understand about available commands.

Let’s start CodeIgniter 4 Spark Module Tutorial in depth.

How we can see the available commands of spark?

Simply back to terminal or command prompt, go to project setup and type command –

$ php spark

Now, we can see the list of commands – list, namespaces, routes, serve etc. These are commands which we can use and perform their respective functions.

Each command having their own scope of work.

By the help of spark CLI we can also work with database.

In the above image, you can see a section is there called Database. In that section commands available as – db:seed, migrate, migrate:create etc.

Start development Server – CodeIgniter 4 Spark

To understand this development server concept, suppose we have an application in CodeIgniter 4. We want to execute this application.

So, we can run that application by means of two different ways.

  1. By URL
  2. Using spark command [new]

By URL is the simplest way to run project into browser. In simple terms copy the path of project, go to your browser and type into address bar and open. It’s pretty simple.

Let’s see how can we use spark command to run, It will be more interesting to know –

Back to terminal and/or command prompt >> Open project folder >> Type Command $ php spark serve

It outputs at terminal –

We can see clearly in the above image about starting of development server. CodeIgniter development server started on http://localhost:8080

By default spark started at localhost with port 8080. In case suppose this port is busy some where to serve some other applications, then this port management will be automatically handled by spark. Spark will choose some other port to start development server.

But in some cases we want to choose our own port to run application. Let’s see how can we do –

Run application at different port

$ php spark serve -port 8089

CodeIgniter development server started on http://localhost:8089

This will start development server of application at port 8089.

To cancel the running development server, press Ctrl + C. It will the stop the server.

When we should use this Development server ?

As we have discussed previously, about starting a development server. This command $ php spark serve is useful where we are doing local development of any project. In the process of application deploy at production server, URL based concept should be used to run the application. We will not serve application by spark.

When you create application in CodeIgniter 4, it includes /public into URL and added index.php with every route. In the production mode of application these things should be removed to make neat & clean URL for SEO point of view.

CodeIgniter Panel of Spark Command List

As we have run the command $ php spark, we have the list of commands divided into two sections CodeIgniter & Database.

To learn for CodeIgniter 4 Generators with v4.1.1, Click here.

The first section is CodeIgniter, which looks something like this –

CodeIgniter
  help               Displays basic usage information.
  list               Lists the available commands.
  namespaces         Verifies your namespaces are setup correctly.
  routes             Displays all of user-defined routes. Does NOT display auto-detected routes.
  serve              Launches the CodeIgniter PHP-Development Server.
  session:migration  Generates the migration file for database sessions.

How to run Commands in Spark

If suppose, we don’t have any idea to run any command, simply type command as –

$ php spark <command-name>

For Example:

help command

$ php spark help

This command will open it’s interface i.e how can we use this. help command – It opens the help manual of any command.

Syntax –

$ php spark help <command_name>

If we want help regarding let’s say command serve. Then we should use like

$ php spark help serve
CodeIgniter CLI Tool - Version 4.0.3 - Server-Time: 2020-08-31 05:12:54am

Description:
   Launches the CodeIgniter PHP-Development Server.

Usage:
   serve

Options:
   -php       The PHP Binary [default: "PHP_BINARY"]
   -host      The HTTP Host [default: "localhost"]
   -port      The HTTP Host Port [default: "8080"]

We can say it provides a short description about available command and their usage. Inside this documentation we have an idea about the parameters or options that we need to run a specific command.

routes command

Fetch all the application routes – We can do by using this routes command. Help manual Command – $ php spark help routes

Short Description: Displays all of user-defined routes. Does NOT display auto-detected routes.

Command –

$ php spark routes

Output –

It list all the application routes what we have developed inside /app/Config/Routes.php

If we open the Routes.php file –

//...

$routes->get('/', 'Home::index');
$routes->get('about-us', 'Site::aboutUs');
$routes->get('contact-us', 'Site::Contact');
$routes->match(["get", "post"], 'my-form', 'Site::myForm');

//...

list command

List command exactly works like $ php spark. This simply returns the list of all available commands.

$ php spark list

Database Section Commands – Spark Module

Database section commands are responsible to handle database related operations. These operations as per command list includes – Migration related command & Seeders commands.

Migration commands – These command help developers to control over the database tables – create table scheme or table structure with the help of PHP file. This technique is much flexible to create or remove tables . We can also create tables by using PhpMyAdmin manual tool.

To learn in Migration of CodeIgniter 4 with v4.1.1 click here.

Seeders commands – Commands which seeds dummy data or test data into table know as seeds command. By the help of seeders we can import 1000+ test rows which helps in application testing.

Learn for Seeders in CodeIgniter 4 with v4.1.1, Click here.

Have a look, the command pallet of database –

Database
  db:seed            Runs the specified seeder to populate known data into the database.
  migrate            Locates and runs all new migrations against the database.
  migrate:create     Creates a new migration file.
  migrate:refresh    Does a rollback followed by a latest to refresh the current state of the
                     database.
  migrate:rollback   Runs the "down" method for all migrations in the last batch.
  migrate:status     Displays a list of all migrations and whether they've been run or not.
  

Available Commands –

There are several commands inside this pallet. We need to start each command one by one for better understanding. These all commands are related with database. Like for managing table, managing data etc.

Let’s start about explanation of each –

migrate:create

This command creates migration file into application. Migration means creating a file which stores the information of table like for it’s scheme or it’s drop command.

Migration files will be stored inside /app/Database/Migrations path. Every migration file stores two methods – up() & down(). Let’s create first migration file.

Command –

$ php spark migrate:create <migration_name>

Example –

$ php spark migrate:create users

Output –

Name the migration file: users
Created file: App/Database/Migrations/2020-08-31-103049_users.php

<?php namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
	public function up()
	{
		//
	}

	//--------------------------------------------------------------------

	public function down()
	{
		//
	}
}

Users migration file contains two methods as we can see – up() & down(). Up method is used to create table structure at db and down method used to rollback means drop the table from database.

Complete code with up() ad down() method –

<?php namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => true,
                'auto_increment' => true,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
            ],
            'password' => [
                'type' => 'VARCHAR',
                'constraint' => '220',
            ],
            'created_at datetime default current_timestamp',
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

    //--------------------------------------------------------------------

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

We are using $this->forge object for defining table and dropping table.

migrate:status

This command list the status of migration file means they are migrated inside database or they are simply created. If we migrate any migration file into database then it’s status will be ON else it will be OFF or blank.

When we migrate migrations into table we will see a extra table will be created named as migrations. Hold we will see this topic in seconds.

migrate

We have created migrations, right. Now, it’s time to migrate into database. Migrate command will help to migrate migrations into database. It creates table. When we run this command up() method will be called.

Command –

$ php spark migrate

Inside above image we can understand each thing please look very carefully. We have used commands of getting status and running migrations.

When we migrate migrations, it creates table along with a extra table called migrations. If migration already in working then table will be updated otherwise for the first migration, this table automatically created by Migration.

This table is used to keep track of the migrations and it’s status.

migrate:rollback

As discussed previously, rollback command is used to revert latest migration from database. So, this command will drop table. While running this command down() method of migration file will work.

Command –

$ php spark migrate:rollback

How can we create a Seeder File –

Seeder file stored inside /app/Database/Seeds. Seeder files are those files which helps to seed dummy data to database table. Seeder files will created as –

<?php 
  
namespace App\Database\Seeds;

class UserSeeder extends \CodeIgniter\Database\Seeder
{
    public function run()
    {
        $data = [
            'name' => 'Sanjay Kumar',
            'email' => 'sanjayk@gmail.com',
            'password' => "12345678",
        ];

        // Simple Queries
        $this->db->query("INSERT INTO users (name, email, password) VALUES(:username:, :email:, :password:)",
            $data
        );

        // Using Query Builder
        $this->db->table('users')->insert($data);
    }
}

Class will extends \CodeIgniter\Database\Seeder

db:seed

This command seeds dummy data by using seeder file. Let’s run the previously created seeder file.

Command –

$ php spark db:seed

After running this command it will insert a new data row inside users table.

This tutorial is not yet complete because the development of CodeIgniter 4 is not yet finalised by community. This is only for the version 4.0.3 yet more to be come. In future we hope more to see in this command list to manage everything by Spark CLI.

Learn CodeIgniter 4 Scaffolding ferature of v4.1.1.

We hope this article helped you to learn about CodeIgniter 4 Spark CLI Command Tutorial 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.

2 thoughts on “CodeIgniter 4 How To Work with Spark CLI Tutorial”

  1. I think the admin of this site is in fact working hard in support of his web site,
    since here every material is quality based material.

Comments are closed.