Skip to content

Latest commit

 

History

History
992 lines (728 loc) · 20 KB

File metadata and controls

992 lines (728 loc) · 20 KB

EasyAPP CLI Guide

Unified Command Line Interface

The EasyAPP CLI tool provides a unified interface for all framework operations including migrations, code generation, testing, and development utilities.


Table of Contents

  1. Getting Started
  2. Installation & Setup
  3. Command Structure
  4. Migration Commands
  5. Generator Commands
  6. Test Commands
  7. Utility Commands
  8. Development Server
  9. Command Reference
  10. Advanced Usage
  11. Troubleshooting

Getting Started

Quick Start

The EasyAPP CLI follows modern framework conventions with grouped commands and intuitive syntax:

# Show all available commands
php easy help

# Check migration status
php easy migrate:status

# Create a new controller
php easy make:controller UserController

# Run tests
php easy test

# Start development server
php easy serve

Basic Syntax

php easy <command> [arguments] [options]

Examples:

php easy migrate                    # Run migrations
php easy migrate:create AddUsers    # Create migration
php easy make:controller User       # Generate controller
php easy test --unit               # Run unit tests
php easy serve --port=9000         # Start server on port 9000

Installation & Setup

Prerequisites

  • PHP 7.4+ with CLI support
  • EasyAPP Framework installed
  • Database connection configured in config.php
  • Command line access to your project directory

Verification

Check that the CLI tool is working:

# Navigate to your project root
cd /path/to/your/project

# Test CLI access
php easy --version

# Expected output:
# EasyAPP CLI Tool
# EasyAPP Framework v2.0
# Copyright (c) 2022, script-php.ro

Command Structure

Command Groups

Commands are organized into logical groups:

Group Purpose Examples
migrate:* Database migrations migrate, migrate:status, migrate:rollback
make:* Code generation make:controller, make:model, make:service
test:* Testing framework test, test:unit, test:integration
cache:* Cache management cache:clear
Standalone Utilities serve, help

Getting Help

# General help
php easy help

# Command-specific help
php easy migrate --help
php easy make:controller --help

# List all commands
php easy help

Migration Commands

Overview

Database migration commands provide complete schema management:

php easy migrate:status      # Check migration status
php easy migrate             # Run pending migrations  
php easy migrate:create      # Create new migration
php easy migrate:rollback    # Rollback migrations

migrate:status

Show current migration state and history:

php easy migrate:status

Output:

Migration Status
======================================================================
Database: my_app_db
Current Version: 3
Latest Version: 5
Total Migrations: 5
Applied: 3
Pending: 2

Version  Status      Description                           Applied At
--------------------------------------------------------------------------------
1        Applied     Create Initial User System            2024-01-01 10:00:00
2        Applied     Add Product System                    2024-01-02 11:30:00  
3        Applied     Add User Address Support              2024-01-03 09:15:00
4        Pending     Transform User Data Example           -
5        Pending     Add Order Management System           -

migrate

Execute pending migrations:

# Run all pending migrations
php easy migrate

# Run to specific version
php easy migrate --to=5

# Preview changes without applying
php easy migrate --dry-run

# Run to specific version in dry-run mode
php easy migrate --to=3 --dry-run

Example Output:

Running Migrations
==================================================
[SUCCESS] Migration_004_TransformUserData (45ms)
   Transform User Data Example
[SUCCESS] Migration_005_AddOrderSystem (120ms)
   Add Order Management System

Summary:
  Executed: 2
  Errors: 0
  Total time: 165ms

All migrations completed successfully!

migrate:create

Generate new migration files:

# Create migration with descriptive name
php easy migrate:create CreateUsersTable
php easy migrate:create AddEmailToUsers
php easy migrate:create UpdateProductPricing

Output:

Creating New Migration
==================================================
Created migration file: 006_add_email_verification.php
Path: /project/migrations/006_add_email_verification.php

Next steps:
1. Edit the migration file to implement up() and down() methods
2. Run 'php easy migrate' to apply the migration

migrate:rollback

Revert migrations to previous state:

# Rollback to specific version
php easy migrate:rollback 3

# Preview rollback changes
php easy migrate:rollback 3 --dry-run

Example Output:

Rolling Back Migrations
==================================================
Rolling back to version: 3
[ROLLBACK] Migration_005_AddOrderSystem (89ms)
   Add Order Management System
[ROLLBACK] Migration_004_TransformUserData (34ms)
   Transform User Data Example

Summary:
  Rolled back: 2
  Errors: 0
  Total time: 123ms

Rollback completed successfully!

Generator Commands

Overview

Code generation commands create boilerplate files following framework conventions:

php easy make:controller     # Generate controller class
php easy make:model         # Generate model class
php easy make:service       # Generate service class
php easy make:migration     # Alias for migrate:create

make:controller

Generate controller files:

# Create basic controller
php easy make:controller UserController
php easy make:controller ProductController
php easy make:controller Auth

# Creates: app/controller/user.php
# Class: ControllerUser extends Controller

Generated File Structure:

<?php

/**
 * ControllerUser
 * Generated by EasyAPP CLI
 */

class ControllerUser extends Controller {
    
    public function index() {
        // Controller logic here
        $this->load->view('user/index');
    }
    
}

make:model

Generate model files:

# Create model classes
php easy make:model User
php easy make:model Product
php easy make:model Order

# Creates: app/model/user.php
# Class: ModelUser extends Model

Generated File Structure:

<?php

/**
 * ModelUser
 * Generated by EasyAPP CLI
 */

class ModelUser extends Model {
    
    protected $table = 'user';
    
    public function __construct() {
        parent::__construct();
    }
    
}

make:service

Generate service files:

# Create service classes
php easy make:service UserService
php easy make:service EmailService
php easy make:service PaymentService

# Creates: app/service/userservice.php
# Class: UserService extends Service

Generated File Structure:

<?php

/**
 * UserService
 * Generated by EasyAPP CLI
 */

class UserService extends Service {
    
    public function __construct() {
        parent::__construct();
    }
    
}

Test Commands

Overview

Testing commands provide simple test execution using the streamlined TestCase framework:

php easy test              # Run all tests
php easy test:unit         # Run unit tests only
php easy test:integration  # Run integration tests only

test

Execute complete test suite (all unit and integration tests):

# Run all available tests
php easy test

Example Output:

Running All Tests
==================================================
Found 3 test file(s)

Running: UserTest.php [PASSED]
Running: SecurityTest.php [PASSED]  
Running: IntegrationTest.php [PASSED]

==================================================
Test Results Summary
==================================================
Total Tests: 3
Passed: 3
Failed: 0

✅ All tests passed!

test:unit

Execute only unit tests (fast, isolated component testing):

# Run only unit tests
php easy test:unit

What Unit Tests Do:

  • Test individual components in isolation
  • Mock external dependencies (no database calls)
  • Execute very quickly (milliseconds per test)
  • Focus on pure logic validation
  • Ideal for TDD and rapid feedback during development

Example Output:

Running Unit Tests
===================================================
Unit tests focus on individual components in isolation
- Fast execution (milliseconds)
- No external dependencies (database, APIs)
- Pure logic validation

Found 1 test file(s)

Running: UserValidationTest.php
==================================================
Running tests for UserValidationTest
==================================================
✓ testEmailValidation
✓ testPasswordStrength
✓ testUsernameValidation
✓ testDataSanitization

Results: 4/4 tests passed
[PASSED]

===================================================
Unit Tests Summary:
===================================================
Total Tests: 1
Passed: 1
Failed: 0

All Unit Tests completed successfully!

test:integration

Execute only integration tests (slower, full system testing):

# Run only integration tests
php easy test:integration

What Integration Tests Do:

  • Test component interaction with real dependencies
  • Use actual database connections and file system
  • Execute slower (seconds per test) due to I/O operations
  • Verify end-to-end workflows and data persistence
  • Essential for deployment validation and system verification

Example Output:

Running Integration Tests
===================================================
Integration tests verify component interaction
- Slower execution (seconds)
- Uses real dependencies (database, files)
- End-to-end workflow validation

Found 2 test file(s)

Running: DatabaseIntegrationTest.php [PASSED]
Running: SystemIntegrationTest.php [PASSED]

===================================================
Integration Tests Summary:
===================================================
Total Tests: 2
Passed: 2
Failed: 0

All Integration Tests completed successfully!

Test Organization

The CLI testing system automatically categorizes tests based on:

Unit Test Detection:

  • Filename contains 'Unit' or 'unit'
  • File content focuses on pure logic without database calls
  • Uses only assertion methods without external dependencies

Integration Test Detection:

  • Filename contains 'Integration' or 'integration'
  • File content includes database operations ($this->db)
  • Uses framework functionality and real dependencies
  • Tests real component interaction

Simple Architecture:

  • TestCase: Core testing class with framework access and assertions
  • CLI Integration: Direct test execution through system/Cli.php
  • No Complex Dependencies: Streamlined execution without heavy infrastructure

Test File Examples:

tests/
├── UserValidationUnitTest.php          # Unit test
├── DatabaseIntegrationTest.php         # Integration test
└── ExampleTest.php                     # Unit test (detected)

Framework Integration

Tests have full access to the EasyAPP Framework through the TestCase class:

class MyTest extends TestCase {
    public function __construct($registry = null) {
        parent::__construct($registry); // Framework access provided
    }
    
    public function testFrameworkAccess() {
        // Direct access to models, services, database, etc.
        $this->assertTrue($this->registry->has('db'));
        $users = $this->load->model('user')->getAll();
        $this->assertTrue(is_array($users));
    }
}

Utility Commands

cache:clear

Clear application cache:

php easy cache:clear

Output:

Clearing Cache
====================
Cleared 47 cache files

What it clears:

  • All files in storage/cache/ directory
  • Compiled templates
  • Cached configuration
  • Session cache files

Development Server

serve

Start the built-in development server:

# Start server on default port (8000)
php easy serve

# Start on specific port
php easy serve --port=9000

# Start on specific host and port
php easy serve --host=0.0.0.0 --port=8080

Default Configuration:

  • Host: 127.0.0.1
  • Port: 8000
  • Document Root: Project root directory

Output:

EasyAPP Development Server
==============================
Server starting at http://127.0.0.1:8000
Press Ctrl+C to stop

Server Options:

# Local development (default)
php easy serve

# Accept external connections
php easy serve --host=0.0.0.0

# Custom port
php easy serve --port=3000

# Specific configuration
php easy serve --host=192.168.1.100 --port=9000

Command Reference

Complete Command List

# Framework Generation Commands
php easy make:controller <name>     # Create controller
php easy make:model <name>          # Create model  
php easy make:service <name>        # Create service
php easy make:migration <name>      # Create migration

# Database Migration Commands  
php easy migrate                    # Run pending migrations
php easy migrate:status             # Show migration status
php easy migrate:rollback <version> # Rollback to version
php easy migrate:create <name>      # Create migration file

# Test Commands
php easy test                       # Run all tests
php easy test:unit                  # Run unit tests
php easy test:integration           # Run integration tests

# Cache Commands
php easy cache:clear                # Clear application cache

# Development Server
php easy serve                      # Start development server

# Utility Commands  
php easy help                       # Show help information
php easy --version                  # Show version information

Global Options

Available for most commands:

--help, -h        # Show command-specific help
--dry-run         # Preview changes without applying (migrations)
--verbose, -v     # Increase output verbosity

Migration-Specific Options

# Migration execution options
--to=<version>    # Migrate to specific version
--dry-run         # Preview without applying changes

# Migration creation options
<name>            # Descriptive migration name (required)

Server Options

--host=<host>     # Bind to specific host (default: 127.0.0.1)
--port=<port>     # Listen on specific port (default: 8000)

Advanced Usage

Automation & Scripting

Deployment Scripts

#!/bin/bash
# deploy.sh - Automated deployment script

echo "Deploying application..."

# Clear cache
php easy cache:clear

# Run migrations
php easy migrate

# Run tests
php easy test

echo "Deployment complete!"

Development Workflow

#!/bin/bash
# dev-setup.sh - Development environment setup

# Create basic application structure
php easy make:controller HomeController
php easy make:model User
php easy make:service AuthService

# Create initial migration
php easy migrate:create SetupInitialDatabase

# Start development server
php easy serve --port=8080

CI/CD Integration

GitHub Actions Example

name: EasyAPP Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.0'
      - name: Run Tests
        run: |
          php easy migrate
          php easy test

Multiple Environments

Environment-Specific Commands

# Development
php easy migrate:status
php easy serve

# Testing  
php easy migrate --dry-run
php easy test

# Production
php easy migrate --to=latest
php easy cache:clear

Troubleshooting

Common Issues

Command Not Found

Problem: php easy command not recognized

Solution:

# Ensure you're in the project root directory
pwd
ls -la easy

# Check PHP CLI is available
php --version

# Verify file permissions (Unix/Linux)
chmod +x easy

Database Connection Errors

Problem: Migration commands fail with database errors

Solution:

# Check database configuration
cat config.php | grep -i db

# Test database connectivity
php -r "new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');"

# Verify database credentials
php easy migrate:status

Permission Errors

Problem: Cannot write to directories

Solution:

# Check directory permissions
ls -la storage/
ls -la migrations/

# Fix permissions (Unix/Linux)
chmod -R 755 storage/
chmod -R 755 migrations/

# Verify web server user permissions
chown -R www-data:www-data storage/

Performance Issues

Large Migration Files

# Use dry-run to preview large migrations
php easy migrate --dry-run

# Run specific migration only
php easy migrate --to=5

# Monitor migration progress
php easy migrate:status

Slow Test Execution

# Run specific test types
php easy test:unit

# Clear cache before testing
php easy cache:clear && php easy test

Debug Mode

Enable debug output for troubleshooting:

# Enable debug in config.php
define('CONFIG_DEBUG', true);

# Run commands to see detailed output
php easy migrate --dry-run
php easy test --verbose

CLI Best Practices

Development Workflow

  1. Start New Features:

    php easy make:controller FeatureController
    php easy make:model FeatureModel
    php easy migrate:create AddFeatureTables
  2. Test Changes:

    php easy migrate --dry-run
    php easy test
  3. Deploy Updates:

    php easy cache:clear
    php easy migrate

Code Organization

  • Use descriptive names for generated files
  • Group related functionality in services
  • Create atomic migrations with single responsibilities
  • Test all generated code before deployment

Security Considerations

  • Never run CLI commands as root in production
  • Validate database credentials before migrations
  • Use dry-run mode for production deployments
  • Backup databases before major migrations

Integration Examples

IDE Integration

VS Code Tasks

Create .vscode/tasks.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "EasyAPP: Run Migrations",
            "type": "shell",
            "command": "php",
            "args": ["easy", "migrate"],
            "group": "build"
        },
        {
            "label": "EasyAPP: Start Server",
            "type": "shell",
            "command": "php",
            "args": ["easy", "serve"],
            "group": "build",
            "isBackground": true
        }
    ]
}

Makefile Integration

Create Makefile:

.PHONY: migrate test serve clean

migrate:
	php easy migrate

migrate-status:
	php easy migrate:status

test:
	php easy test

serve:
	php easy serve

clean:
	php easy cache:clear

deploy: clean migrate test
	@echo "Deployment complete"

Usage:

make migrate
make test
make serve
make deploy

Summary

The EasyAPP CLI provides a comprehensive, unified interface for all framework operations:

Key Benefits:

  • Unified Interface: Single command for all operations
  • Industry Standards: Follows Laravel/Symfony conventions
  • Professional Output: Clear, colorized feedback
  • Comprehensive Help: Built-in documentation
  • Development Focus: Streamlined developer experience

Command Groups:

  • Migration: migrate:* - Database schema management
  • Generation: make:* - Code scaffolding and boilerplate
  • Testing: test:* - Test execution and validation
  • Utilities: Cache management and development server

Next Steps:

  1. Explore Commands: Try php easy help
  2. Create Components: Use make:* commands
  3. Manage Database: Use migrate:* commands
  4. Develop Locally: Use php easy serve
  5. Automate Workflows: Integrate with CI/CD

The unified CLI interface makes EasyAPP development faster, more consistent, and follows modern framework best practices.