Luminova Framework

PHP Luminova: Build a CLI CRUD Interface for Blog Posts

Last updated: 2026-11-28 20:57:12

List, read, create, update, and delete blog posts from the terminal with Luminova.

This example builds a routable CLI controller for managing a posts table. Configure a development database, choose one routing style, then add the model, migration, seeder, and controller handlers. Run the sample commands against test data. See the CLI Command Routing.

Command API Example

For working implementation example and source code, visit GitHub: Luminova HTTP and CLI REST API Examples.


Requirements

Before you begin, make sure you have:

  • Luminova PHP Framework: Install the latest version or update your current version.
  • Command-Line Tool: Any command-line tool (e.g., Terminal, Command Prompt).
  • Database: A configured database (e.g., MySQL) in your environment.

Step 1: Define Command Routes

In Luminova, routes connect client commands to specific controller actions, just like in an HTTP API.

Current source limitation: The router can fail before invoking grouped command handlers in either routing style. Both styles use the same dispatcher. The registration and handler examples below show the APIs independently of that framework issue.

Attribute-Based Routing

Set feature.route.attributes = enable in .env and keep Boot::http()->router->context()->run() in public/index.php. Put the following controller in app/Controllers/Cli/. The #[Group] attribute sets the first command word, and each #[Command] names the action.

// /app/Controllers/Cli/PostsCommand.php

namespace App\Controllers\Cli;

use JsonException;
use App\Models\Posts;
use function Luminova\Funcs\uuid;
use Luminova\Attributes\Group;
use Luminova\Command\Terminal;
use Luminova\Attributes\Command;
use Luminova\Command\Utils\Text;
use Luminova\Command\Utils\Color;
use Luminova\Base\Cli\AbstractController;

#[Group(name: 'posts')]
class PostsCommand extends AbstractController
{
    /**
     * Command group associated with posts.
     */
    protected string $group = 'posts';

    /**
     * Command name for identifying this CLI tool.
     */
    protected string $name  = 'post-command';

    /**
     * Instance of the Posts model for CRUD operations.
     *
     * @var Posts|null $posts
     */
    private static ?Posts $posts = null;

    /**
     * Initializes the `Posts` model instance on command creation.
     */
    protected function onCreate(): void
    {
        self::$posts ??= new Posts();
    }

    /**
     * Displays help information for post command.
     */
    public function help(array $helps): int
    {
        Terminal::helper($helps);
        return STATUS_SUCCESS;
    }

    #[Command('list', group: 'posts')]
    public function list(): int
    {
        // Replace this method with the implementation in Step 4.
        return STATUS_ERROR;
    }

    #[Command('get', group: 'posts')]
    public function show(): int
    {
        // Replace this method with the implementation in Step 4.
        return STATUS_ERROR;
    }

    #[Command('create', group: 'posts')]
    public function create(): int
    {
        // Replace this method with the implementation in Step 4.
        return STATUS_ERROR;
    }

    #[Command('update', group: 'posts')]
    public function update(): int
    {
        // Replace this method with the implementation in Step 4.
        return STATUS_ERROR;
    }

    #[Command('delete', group: 'posts')]
    public function delete(): int
    {
        // Replace this method with the implementation in Step 4.
        return STATUS_ERROR;
    }

    #[Command(middleware: Command::GROUP_MIDDLEWARE, group: 'posts')]
    public function auth(): int
    {
        return getenv('LUMINOVA_POSTS_DEMO') === '1' ? STATUS_SUCCESS : STATUS_ERROR;
    }
}

Method-Based Routing

For method-based routing, set feature.route.attributes = disable in .env, remove the class and method attributes, and register the equivalent routes in the route file. In this approach, CLI routes are defined within the /routes/cli.php file. Add new Prefix(Prefix::CLI, isCommand: true) to the array passed to context() in public/index.php, using Luminova\Routing\Prefix. Keep your existing HTTP contexts in that array. Router::group() connects the posts group to the controller methods.

// /routes/cli.php

use Luminova\Routing\Router;

Router::group('posts', static function () {
    Router::guard('posts', 'PostsCommand::auth');

    // CRUD routes for posts
    Router::command('/list', 'PostsCommand::list');         // Retrieve all posts
    Router::command('/get', 'PostsCommand::show');          // Retrieve a specific post by ID
    Router::command('/create', 'PostsCommand::create');     // Create a new post
    Router::command('/update', 'PostsCommand::update');     // Update an existing post
    Router::command('/delete', 'PostsCommand::delete');     // Delete a post by ID
});

Local demo guard
Both routing styles call auth() before running a posts command. In Bash or Zsh, run export LUMINOVA_POSTS_DEMO=1 to enable the demo in your current shell. This switch is for local development with test data.


Step 2: Define Post Model

The model maps Posts to the posts table and uses pid as its primary key. Its $updatable list includes the timestamp written by the update command.

// /app/Models/Posts.php

namespace App\Models;

use Luminova\Base\Database\AbstractModel;

class Posts extends AbstractModel
{
    protected string $table = 'posts';  // Database table
    /**
     * @var string[]
     */
    protected array $updatable = ['post_title', 'post_body', 'updated_on'];  // Updatable fields
    protected string $primaryKey = 'pid';  // Primary key
}

Step 3: Set Up Database Migrations and Seeders

1. Create the Migration Class:

Define your migration class to structure the database table.

// /app/Database/Migrations/PostsMigration.php

namespace App\Database\Migrations;

use Luminova\Database\Table;
use Luminova\Database\Schema;
use Luminova\Database\Migration;

class PostsMigration extends Migration
{
    /**
     * Defines the 'posts' table structure.
     */
    public function up(): bool
    {
        return Schema::create('posts', function (Table $table) {
            $table->prettify = true;
            $table->database = Table::SQLITE;

            $table->id('pid');
            $table->uuid('post_uuid')->nullable(false)->unique();
            $table->integer('user_id')->nullable(false);
            $table->string('post_title')->nullable(false);
            $table->string('post_image')->nullable();
            $table->text('post_body')->nullable(false);
            $table->timestamps();

            return $table;
        });
    }

    public function down(): bool
    {
        return Schema::dropIfExists('posts');
    }

    public function alter(): bool
    {
        return true;
    }
}

2. Create the Seeder Class:

Add seed data to populate your posts table.

// /app/Database/Seeders/PostsSeeder.php

namespace App\Database\Seeders;

use function Luminova\Funcs\uuid;
use Luminova\Database\Seeder;
use Luminova\Database\Query\Builder;

class PostsSeeder extends Seeder
{
    /**
     * Inserts sample data into 'posts' table.
     */
    public function run(Builder $builder): int
    {
        return $builder->from('posts')->insert([
            [
                'post_uuid' => uuid(),
                'user_id' => 101,
                'post_title' => 'Getting Started with PHP Luminova',
                'post_body' => 'Learn the basics of setting up and running your first project with PHP Luminova framework.',
            ],
            /* Additional seed data */
        ]);
    }
}

3. Configure Database Connection:

Set up your database configuration in the .env file. Here, SQLITE is used as an example.

# /.env

database.connection = pdo
database.hostname = localhost
database.pdo.driver = sqlite
database.sqlite.path = /writeable/database/development.sqlite

Enable PHP's pdo_sqlite extension and make sure writeable/database/ exists and is writable. Run the migration, seeder, and example commands from the same project root.

4. Run Migrations and Seeders:

Once configured, run migrations first:

php novakit db:migrate --class=PostsMigration

After a successful migration, seed the database:

php novakit db:seed --class=PostsSeeder

Step 4: Implement Controller Methods for CRUD Operations

In the PostsCommand controller, each method performs a specific CRUD operation, responding to CLI commands and interacting with the Posts model.

Note: Replace each placeholder method with the matching implementation below. Keep the controller imports and, for attribute routing, retain the attributes above the methods. Run posts list to find the IDs in your test database. The commands below use the first seeded row, which has ID 1 in a fresh database.


list

Retrieve All Posts:

Fetches a list of all posts from the database, with optional arguments --limit or short -l to specify the number of posts to retrieve, and --offset or short -o to define the starting point for the result set.

public function list(): int
{
    $limit = filter_var($this->option('limit', 'l', 10), FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1, 'max_range' => 100],
    ]);
    $offset = filter_var($this->option('offset', 'o', 0), FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 0],
    ]);

    if ($limit === false || $offset === false) {
        Terminal::error('Use a limit from 1 to 100 and a non-negative offset.');
        return STATUS_ERROR;
    }

    $items = self::$posts->select(limit: $limit, offset: $offset);

    if (!$items) {
        Terminal::writeln('No posts found.');
        return STATUS_SUCCESS;
    }

    Terminal::writeln(Color::apply('LIST POSTS', Text::FONT_BOLD, 'red'));
    Terminal::newLine();

    foreach ($items as $item) {
        Terminal::writeln(
            Color::style(str_pad('[' . $item->pid . '] ', 10), 'green') . $item->post_title
        );
    }

    Terminal::newLine();
    Terminal::writeln('To read a post, run: "php public/index.php posts get --post-id=<n>"');
    return STATUS_SUCCESS;
}

This method retrieves and displays a paginated list of posts, allowing users to limit and offset the results using command-line arguments. If no posts are found, it will return an error message.

Run from the project root

php public/index.php posts list --limit=10 --offset=0

get

Retrieve a Single Post:

Fetches and displays a specific post by its unique identifier, using the --post-id or short flag -p argument. If the post exists, it shows the title, body, and related metadata.

public function show(): int
{
    $pid = filter_var($this->option('post-id', 'p'), FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1],
    ]);
    if ($pid === false) {
        Terminal::error('Pass a positive integer with --post-id or -p.');
        return STATUS_ERROR;
    }

    $item = self::$posts->where('pid', '=', $pid)->find()->get();

    if ($item) {
        Terminal::writeln(Color::apply($item->post_title, Text::FONT_BOLD, 'red'));
        Terminal::writeln($item->post_body);
        Terminal::newLine();
        Terminal::writeln(Color::apply('About Post', Text::FONT_BOLD|Text::FONT_UNDERLINE, 'cyan'));
        $details = [
            'User ID' => $item->user_id,
            'Post ID' => $item->pid,
            'Created' => $item->created_on ?? '—',
            'Updated' => $item->updated_on ?? '—',
        ];
        Terminal::writeln(Terminal::table([$details]));

        return STATUS_SUCCESS;
    }

    Terminal::error("Post with id: {$pid} not found.");
    return STATUS_ERROR;
}

This method retrieves the post based on the post-id argument, and if the post is found, it formats and displays the post details with metadata.

Run from the project root

php public/index.php posts get --post-id=1

create

Create a New Post:

Adds a new post to the database with the specified user ID, title, and body content. Use the --body (or shorthand -b) argument to pass the post details in JSON format.

public function create(): int
{
    $body = $this->option('body', 'b');
    if (!is_string($body) || $body === '') {
        Terminal::error('Pass a JSON object with --body or -b.');
        return STATUS_ERROR;
    }

    try {
        $input = json_decode($body, associative: false, flags: JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        Terminal::error('Invalid JSON body. ' . $e->getMessage());
        return STATUS_ERROR;
    }

    if (
        !is_object($input)
        || !is_int($input->userId ?? null) || $input->userId < 1
        || !is_string($input->title ?? null) || trim($input->title) === ''
        || !is_string($input->body ?? null) || trim($input->body) === ''
    ) {
        Terminal::error('Supply a positive integer userId and non-empty title and body strings.');
        return STATUS_ERROR;
    }

    if (!self::$posts->insert([
        'user_id' => $input->userId,
        'post_title' => $input->title,
        'post_body' => $input->body,
        'post_uuid' => uuid(),
    ])) {
        Terminal::error('Unable to create post.');
        return STATUS_ERROR;
    }

    Terminal::success('Post was successfully created.');
    return STATUS_SUCCESS;
}

This method validates and decodes the JSON input, inserts the new post into the database, and provides feedback on the result.

Run from the project root

php public/index.php posts create --body='{ "userId": 42, "title": "Testing Luminova CLI API client", "body": "Hello world!" }'

update

Update an Existing Post:

Updates an existing post's details using the provided post-id and content in JSON format. Specify the --post-id (or shorthand -p) for the post's unique identifier and --body (or shorthand -b) to pass the new details in JSON.

public function update(): int
{
    $pid = filter_var($this->option('post-id', 'p'), FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1],
    ]);
    $body = $this->option('body', 'b');

    if ($pid === false || !is_string($body) || $body === '') {
        Terminal::error('Pass a positive --post-id and a JSON object with --body.');
        return STATUS_ERROR;
    }

    try {
        $input = json_decode($body, associative: false, flags: JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        Terminal::error('Invalid JSON body. ' . $e->getMessage());
        return STATUS_ERROR;
    }

    if (!is_object($input)) {
        Terminal::error('The update body must be a JSON object.');
        return STATUS_ERROR;
    }

    $changes = [];
    foreach (['title' => 'post_title', 'body' => 'post_body'] as $field => $column) {
        if (!property_exists($input, $field)) {
            continue;
        }

        if (!is_string($input->$field) || trim($input->$field) === '') {
            Terminal::error("The {$field} must be a non-empty string.");
            return STATUS_ERROR;
        }

        $changes[$column] = $input->$field;
    }

    if ($changes === []) {
        Terminal::writeln("Nothing to update on post ID {$pid}.", 'yellow');
        return STATUS_SUCCESS;
    }

    $changes['updated_on'] = date('Y-m-d H:i:s');
    $post = new Posts($pid);

    if ($post->update($pid, $changes) === null) {
        Terminal::error("No changes were saved for post ID {$pid}.");
        return STATUS_ERROR;
    }

    Terminal::success("Post ID {$pid} was successfully updated.");
    return STATUS_SUCCESS;
}

This method updates only the supplied title or body. Omitted fields retain their current values. It outputs success or error messages based on the result.

Run from the project root

php public/index.php posts update --post-id=1 --body='{"title": "Testing Updated Luminova CLI API client" }'

delete

Delete a Post:

Deletes a post from the database based on a provided post-id. Use the argument --post-id (or -p for shorthand) to specify the post's unique identifier.

public function delete(): int
{
    $pid = filter_var($this->option('post-id', 'p'), FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1],
    ]);
    if ($pid === false) {
        Terminal::error('Pass a positive integer with --post-id or -p.');
        return STATUS_ERROR;
    }

    if(self::$posts->delete($pid)){
        Terminal::success("Post ID: {$pid} was successfully deleted.");
        return STATUS_SUCCESS;
    }

    Terminal::error("Unable to delete Post ID: {$pid}.");
    return STATUS_ERROR;
}

This method validates the post-id, attempts to delete the post, and outputs a success or error message based on the result.

Run from the project root

php public/index.php posts delete --post-id=1

Remote Execution

Using SSH Manually:

To manually execute commands on a remote server over SSH, use the following commands:

ssh -i ~/.ssh/your-key [email protected]
cd /path/to/your/project
php public/index.php posts list

Run the example using an SSH account authorized to access the deployed application. The command runs under that account on the remote server.