Cookbook

Console Commands

Glueful’s Symfony Console-based CLI with DI-enabled commands for cache, database, extensions, queues, security, system checks, and development tools.

This comprehensive guide covers Glueful's console system, built on Symfony Console with enhanced features for modern PHP development and enterprise-grade application management.

Table of Contents

  1. Overview
  2. Console Architecture
  3. Command Categories
  4. Development Commands
  5. Database Management
  6. Cache Operations
  7. Extension Management
  8. Queue Management
  9. Security Commands
  10. System Utilities
  11. Field Selection Commands
  12. Container/DI Commands
  13. Configuration Commands
  14. Code Generation
  15. Notifications
  16. Installation
  17. Custom Commands
  18. Best Practices

Overview

Glueful's console system provides a powerful command-line interface for application management, built on Symfony Console with dependency injection integration and enhanced features for modern development workflows.

Key Features

  • Symfony Console Integration: Modern CLI framework with advanced features
  • Dependency Injection: Full DI container integration for all commands
  • Enhanced Styling: SymfonyStyle integration with custom styling helpers
  • Interactive Commands: Rich user interaction with confirmations, choices, and progress bars
  • Production Safety: Built-in production environment safeguards
  • Extensible Architecture: Easy custom command creation with base classes
  • Multi-format Output: Support for table, JSON, and compact output formats

Console Architecture

The console system is built around several key components:

  1. Application: Central console application managing all commands
  2. BaseCommand: Enhanced base class with DI integration and styling
  3. Command Registry: Automatic command discovery and registration
  4. Service Integration: Full access to application services and utilities

Console Architecture

Application Class

use Glueful\Console\Application;

$container = container();
$app = new Application($container);
$app->run();

Key Features:

  • Automatic command registration via DI container
  • Enhanced error handling and exception management
  • Consistent branding and help system
  • Command categorization and organization

BaseCommand Class

All Glueful commands extend the enhanced BaseCommand:

use Glueful\Console\BaseCommand;

class MyCommand extends BaseCommand
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->info('Starting operation...');
        $this->success('Operation completed!');
        return self::SUCCESS;
    }
}

Enhanced Methods:

Output Methods:

  • $this->success($message) - Green success message with icon
  • $this->error($message) - Red error message with icon
  • $this->warning($message) - Yellow warning message with icon
  • $this->info($message) - Blue info message
  • $this->note($message) - Highlighted note/tip
  • $this->tip($message) - Legacy tip method (adds "Tip:" prefix)
  • $this->line($message) - Plain text line

Interactive Methods:

  • $this->confirm($question, $default) - Yes/no confirmation
  • $this->ask($question, $default) - Text input with optional default
  • $this->secret($question) - Hidden input for passwords
  • $this->choice($question, $choices, $default) - Multiple choice selection

Display Methods:

  • $this->table($headers, $rows) - Formatted table display
  • $this->createProgressBar($max) - Create progress bar instance
  • $this->progressBar($steps, $callback) - Progress bar with callback

Utility Methods:

  • $this->getService($serviceId) - Resolve service from DI container
  • $this->getServiceDynamic($serviceId) - Dynamic service resolution
  • $this->getContainer() - Access DI container
  • $this->isProduction() - Check if running in production
  • $this->confirmProduction($operation) - Force production confirmation

Command Categories

Available Commands

# View all available commands
php glueful help
php glueful list

# Get help for specific command
php glueful help migrate:run
php glueful system:check --help

Development Commands

Serve Command

Start the built-in development server:

# Start development server
php glueful serve

# Options
php glueful serve --host=0.0.0.0 --port=8080

Features:

  • Port availability checking
  • Host binding configuration and optional browser open
  • Graceful shutdown handling (Ctrl+C)
  • Uses PHP built‑in server with project public/ as document root

Route Commands

Note: Route listing commands are not bundled in the current CLI build. Use your application’s docs or router debug tooling as needed.

Database Management

Migration Commands

Run Migrations

# Run all pending migrations
php glueful migrate:run

# Options
php glueful migrate:run --force           # Skip production confirmation
php glueful migrate:run --dry-run         # Show what would be executed
php glueful migrate:run --batch=5         # Specify batch number

Features:

  • Production safety confirmations
  • Progress bars for multiple migrations
  • Dry-run mode for testing
  • Detailed error reporting

Create Migrations

# Create new migration
php glueful migrate:create CreateUsersTable
php glueful migrate:create AddIndexToUsers

Migration Status

# Check migration status
php glueful migrate:status

# Show detailed information
php glueful migrate:status --detailed

Rollback Migrations

# Rollback last migration
php glueful migrate:rollback

# Rollback specific number of migrations
php glueful migrate:rollback --steps=3

# Rollback to specific batch
php glueful migrate:rollback --batch=2

Database Utilities

Database Status

# Check database connection and status
php glueful db:status

# Show detailed connection information
php glueful db:status --detailed

Database Reset

# Reset database (destructive operation)
php glueful db:reset --force

# Reset with confirmation
php glueful db:reset

Query Profiling

# Profile database queries
php glueful db:profile

# Profile specific operations
php glueful db:profile --operation=migration

Cache Operations

Clear Cache

# Clear all cache
php glueful cache:clear

# Clear specific cache tags
php glueful cache:clear --tag=user-sessions
php glueful cache:clear --tag=api-responses --tag=compiled-views

# Force clear without confirmation
php glueful cache:clear --force

Features:

  • Tag-based cache invalidation
  • Production safety confirmations
  • Multiple cache store support
  • Automatic cache store availability testing

Cache Status

# View cache statistics
php glueful cache:status

# Show detailed cache information
php glueful cache:status --detailed

Cache Operations

# Get cache value
php glueful cache:get user:123

# Set cache value
php glueful cache:set user:123 '{"name":"John"}' --ttl=3600

# Delete cache key
php glueful cache:delete user:123

# Check cache TTL
php glueful cache:ttl user:123

# Set cache expiration
php glueful cache:expire user:123 300

# Purge cache by pattern
php glueful cache:purge "user:*"

Extension Management

Extension Information

# List all extensions
php glueful extensions:info

# Show specific extension details
php glueful extensions:info MyExtension

# Filter by status
php glueful extensions:info --status=enabled
php glueful extensions:info --status=disabled

# Different output formats
php glueful extensions:info --format=json
php glueful extensions:info --format=compact

# Show additional information
php glueful extensions:info --show-autoload
php glueful extensions:info --show-dependencies

Extension Lifecycle

# Enable extension
php glueful extensions:enable MyExtension

# Disable extension
php glueful extensions:disable MyExtension

# Create new extension
php glueful extensions:create MyExtension --type=basic
php glueful extensions:create MyExtension --type=advanced

# Validate extension
php glueful extensions:validate MyExtension

# Install extension from package
php glueful extensions:install /path/to/extension.zip
php glueful extensions:install https://example.com/extension.zip

# Delete extension
php glueful extensions:delete MyExtension --force

Extension Development

# Show extension namespaces
php glueful extensions:info --namespaces

# Check for namespace conflicts
php glueful extensions:info --namespaces --conflicts

# Performance metrics
php glueful extensions:info --namespaces --performance

# Filter namespaces
php glueful extensions:info --namespaces --filter="App\\*"

# Benchmark extensions
php glueful extensions:benchmark

# Debug extension system
php glueful extensions:debug

Extension Listing and Analysis

# List all extensions with detailed information
php glueful extensions:list

# Show extension summary statistics
php glueful extensions:summary

# Show dependency information for an extension
php glueful extensions:why MyExtension

# Show which extensions depend on a specific extension
php glueful extensions:why MyExtension --reverse

Extension Cache Management

# Manage extension cache
php glueful extensions:cache

# Clear extension cache
php glueful extensions:cache --clear

# Rebuild extension cache
php glueful extensions:cache --rebuild

# Show cache statistics
php glueful extensions:cache --stats

# Clear all extension-related caches
php glueful extensions:clear

# Clear specific extension cache
php glueful extensions:clear MyExtension

Queue Management

Queue Workers

# Start queue workers (default: 2 workers)
php glueful queue:work

# Configure worker options
php glueful queue:work --workers=4 --queue=default,high
php glueful queue:work --memory=256 --timeout=120 --max-jobs=500

# Run in daemon mode
php glueful queue:work --daemon

# Stop when queue is empty
php glueful queue:work --stop-when-empty

Advanced Queue Management

# Spawn additional workers
php glueful queue:work spawn --count=2 --queue=email

# Scale workers dynamically
php glueful queue:work scale --count=5 --queue=default

# Check worker status
php glueful queue:work status
php glueful queue:work status --json
php glueful queue:work status --watch=5  # Auto-refresh every 5 seconds

# Stop workers
php glueful queue:work stop --all
php glueful queue:work stop --worker-id=worker-123

# Restart workers
php glueful queue:work restart --all
php glueful queue:work restart --worker-id=worker-123

# Health check
php glueful queue:work health

Auto-scaling

# Start auto-scaling daemon
php glueful queue:autoscale

# Configure scaling parameters
php glueful queue:autoscale --min-workers=2 --max-workers=10
php glueful queue:autoscale --scale-up-threshold=10 --scale-down-threshold=2

# Monitor scaling metrics
php glueful queue:autoscale --status

Queue Scheduler

# Start job scheduler
php glueful queue:scheduler

# Run specific schedule
php glueful queue:scheduler --schedule=daily

Security Commands

Security Checks

# Run comprehensive security scan
php glueful security:check

# Check for vulnerabilities
php glueful security:vulnerabilities

# Scan for security issues
php glueful security:scan --detailed

# Generate security report
php glueful security:report --format=json

Security Management

# Enable lockdown mode
php glueful security:lockdown:enable

# Disable lockdown mode
php glueful security:lockdown:disable

# Reset user password
php glueful security:reset-password [email protected]

# Revoke tokens
php glueful security:revoke-tokens --user=123
php glueful security:revoke-tokens --all

# Check security headers
php glueful security:headers:check

System Utilities

System Check

# Comprehensive system validation
php glueful system:check

# Show detailed information
php glueful system:check --details

# Attempt automatic fixes
php glueful system:check --fix

# Production readiness check
php glueful system:check --production

Validates:

  • PHP version and extensions
  • File permissions and directories
  • Configuration settings
  • Database connectivity
  • Security configuration
  • Production environment settings

Memory Monitoring

# Real-time memory monitoring
php glueful system:memory

# Monitor with custom interval and duration
php glueful system:memory --interval=5 --duration=300

# Monitor specific process
php glueful system:memory --pid=1234

# Set custom thresholds
php glueful system:memory --warning=128M --critical=256M

# Export monitoring data
php glueful system:memory --export=memory-report.json

# Different output formats
php glueful system:memory --format=table
php glueful system:memory --format=json
php glueful system:memory --format=csv

# Send alerts via email or webhook
php glueful system:memory [email protected] --webhook=https://alerts.example.com

Features:

  • Real-time memory usage monitoring
  • Configurable alert thresholds
  • Multiple output formats
  • Data export capabilities
  • Integration with external monitoring systems
  • Process-specific monitoring

Production Commands

# Prepare for production deployment
php glueful system:production

# Optimize for production
php glueful system:production --optimize

# Validate production configuration
php glueful system:production --validate

Version Information

# Show framework version
php glueful version

# Show detailed version information
php glueful version --detailed

# Show all component versions
php glueful version --components

# Export version information
php glueful version --format=json

Displays:

  • Framework version and build information
  • PHP version and loaded extensions
  • Database version and driver information
  • Cache driver version
  • Dependency versions
  • System environment information

Field Selection Commands

For core concepts and API, see Field Selection

Glueful provides sophisticated field selection commands for analyzing and optimizing GraphQL-style field selection patterns in REST APIs.

Field Analysis

# Analyze field usage patterns across the application
php glueful fields:analyze

# Show detailed analysis with optimization suggestions
php glueful fields:analyze --detailed

# Export analysis to JSON
php glueful fields:analyze --export=field-analysis.json

# Analyze specific endpoints only
php glueful fields:analyze --endpoints="/api/users,/api/posts"

Features:

  • Field usage frequency analysis
  • Common pattern identification
  • Performance impact assessment
  • Optimization recommendations
  • Export capabilities for external tools

Field Validation

# Validate field selection configurations
php glueful fields:validate

# Validate with strict mode (fail on warnings)
php glueful fields:validate --strict

# Validate specific routes only
php glueful fields:validate --routes="/api/users/*"

# Show detailed validation results
php glueful fields:validate --detailed

Field Performance Testing

# Run field selection performance tests
php glueful fields:performance

# Test with different dataset sizes
php glueful fields:performance --dataset-size=1000

# Test specific field patterns
php glueful fields:performance --pattern="user(id,name,posts(title))"

# Export performance metrics
php glueful fields:performance --export=performance-report.json

Whitelist Validation

# Check field whitelist compliance
php glueful fields:whitelist-check

# Check specific endpoints
php glueful fields:whitelist-check --endpoint="/api/users"

# Show non-compliant fields
php glueful fields:whitelist-check --show-violations

# Export compliance report
php glueful fields:whitelist-check --export=compliance.json

Container/DI Commands

Advanced dependency injection container management and optimization commands.

Container Compilation

# Compile container for production optimization
php glueful di:container:compile

# Compile with debug information
php glueful di:container:compile --debug

# Force recompilation
php glueful di:container:compile --force

# Show compilation statistics  
php glueful di:container:compile --stats

Features:

  • Pre-compiles all service definitions
  • Optimizes service resolution paths
  • Validates all service configurations
  • Generates optimized container cache
  • Removes debug information for performance

Container Debugging

# Debug container services and dependencies
php glueful di:container:debug

# Show specific service information
php glueful di:container:debug --service="UserService"

# Show circular dependency detection
php glueful di:container:debug --circular-deps

# Export dependency graph
php glueful di:container:debug --graph=dependencies.dot

Container Validation

# Validate container configuration
php glueful di:container:validate

# Validate with strict checking
php glueful di:container:validate --strict

# Show detailed validation results
php glueful di:container:validate --detailed

# Check specific service providers
php glueful di:container:validate --providers="AuthServiceProvider,CacheServiceProvider"

Lazy Services

Inspect and optionally warm lazy service groups.

# Show configured lazy IDs
php glueful di:lazy:status

# Warm background services now
php glueful di:lazy:status --warm-background

# Warm request-time services now
php glueful di:lazy:status --warm-request

# Output as JSON
php glueful di:lazy:status --format=json

Configuration Commands

Tools for managing application configuration, IDE support, and documentation generation.

Generate IDE Support

# Generate IDE configuration and JSON schemas
php glueful config:generate-ide-support

# Generate for specific IDEs
php glueful config:generate-ide-support --ide=phpstorm
php glueful config:generate-ide-support --ide=vscode

# Include JSON schemas for validation
php glueful config:generate-ide-support --schemas

# Custom output directory
php glueful config:generate-ide-support --output=.ide/

Generated Files:

  • PhpStorm configuration files
  • VS Code settings and schemas
  • JSON schemas for configuration validation
  • Autocomplete definitions
  • Code inspection rules

Generate Documentation

# Generate configuration documentation
php glueful config:generate-docs

# Generate in different formats
php glueful config:generate-docs --format=markdown
php glueful config:generate-docs --format=html

# Include examples and defaults
php glueful config:generate-docs --examples --defaults

# Custom template
php glueful config:generate-docs --template=custom.twig

Validate Configuration

# Validate all configuration files
php glueful config:validate

# Validate specific configuration files
php glueful config:validate --files="app,database,cache"

# Show detailed validation results
php glueful config:validate --detailed

# Check for unused configuration options
php glueful config:validate --unused

# Validate against JSON schema
php glueful config:validate --schema

Code Generation

Generate Keys

# Generate all encryption keys
php glueful generate:key

# Generate specific keys
php glueful generate:key --jwt-only
php glueful generate:key --app-only

# Force overwrite existing keys
php glueful generate:key --force

# Show generated keys (not recommended in production)
php glueful generate:key --show

Generate Controllers

# Generate basic controller
php glueful generate:controller UserController

# Generate REST API controller
php glueful generate:controller UserController --api

# Generate with specific methods
php glueful generate:controller UserController --methods=index,show,store

API Documentation

# Generate API definitions
php glueful generate:api-definitions

# Generate API documentation
php glueful generate:api-docs

# Custom database and table
php glueful generate:api-definitions --database=mydb --table=users

Event Scaffolding

Create event and listener classes.

# Create a new event class
php glueful event:create UserRegistered

# Create a new event listener class
php glueful event:listener SendWelcomeEmail

Notifications

Process Notification Retries

# Process queued notification retries
php glueful notifications:process-retries

Installation

Interactive Installer

# Run the installation wizard for a new project
php glueful install

Custom Commands

Creating Custom Commands

<?php

namespace App\Console\Commands;

use Glueful\Console\BaseCommand;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
    name: 'my:command',
    description: 'Custom command description'
)]
class MyCommand extends BaseCommand
{
    protected function configure(): void
    {
        $this->setDescription('Custom command description')
             ->setHelp('Detailed help text for the command')
             ->addArgument(
                 'name',
                 InputArgument::REQUIRED,
                 'Name argument'
             )
             ->addOption(
                 'force',
                 'f',
                 InputOption::VALUE_NONE,
                 'Force execution'
             );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $name = $input->getArgument('name');
        $force = $input->getOption('force');

        // Production safety check
        if (!$force && !$this->confirmProduction('execute custom operation')) {
            return self::FAILURE;
        }

        try {
            $this->info("Starting operation for: {$name}");

            // Access services via DI container
            $myService = $this->getService(MyService::class);
            
            // Progress bar example
            $this->progressBar(10, function ($progressBar) use ($myService) {
                for ($i = 0; $i < 10; $i++) {
                    $myService->doSomething();
                    $progressBar->advance();
                    sleep(1);
                }
            });

            $this->success('Operation completed successfully!');
            return self::SUCCESS;
        } catch (\Exception $e) {
            $this->error('Operation failed: ' . $e->getMessage());
            return self::FAILURE;
        }
    }
}

Registering Custom Commands

// In your service provider or bootstrap file
$app = new Glueful\Console\Application($container);
$app->addCommand(MyCommand::class);

Command Templates

Glueful provides templates for common command patterns:

# Create command from template
php glueful generate:command MyCommand --template=basic
php glueful generate:command MyCommand --template=database
php glueful generate:command MyCommand --template=interactive

Best Practices

Command Design

  1. Use Descriptive Names: Follow the group:action pattern
  2. Provide Good Help: Include detailed descriptions and examples
  3. Handle Errors Gracefully: Use try-catch blocks and meaningful error messages
  4. Production Safety: Always check production environment for destructive operations
  5. Progress Feedback: Use progress bars for long-running operations

Input Validation

protected function execute(InputInterface $input, OutputInterface $output): int
{
    // Validate required options
    $email = $input->getOption('email');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $this->error('Invalid email address provided');
        return self::FAILURE;
    }

    // Validate file paths
    $file = $input->getArgument('file');
    if (!file_exists($file)) {
        $this->error("File not found: {$file}");
        return self::FAILURE;
    }

    return self::SUCCESS;
}

Interactive Commands

protected function execute(InputInterface $input, OutputInterface $output): int
{
    // Confirmation prompts
    if (!$this->confirm('Do you want to continue?', false)) {
        $this->info('Operation cancelled');
        return self::SUCCESS;
    }

    // Choice menus
    $action = $this->choice(
        'What would you like to do?',
        ['create', 'update', 'delete'],
        'create'
    );

    // Text input with validation
    $name = $this->ask('Enter name');
    while (empty($name)) {
        $this->warning('Name cannot be empty');
        $name = $this->ask('Enter name');
    }

    return self::SUCCESS;
}

Output Formatting

protected function execute(InputInterface $input, OutputInterface $output): int
{
    // Table display
    $this->table(
        ['ID', 'Name', 'Status'],
        [
            [1, 'John Doe', 'Active'],
            [2, 'Jane Smith', 'Inactive']
        ]
    );

    // Progress tracking
    $items = range(1, 100);
    $this->progressBar(count($items), function ($progressBar) use ($items) {
        foreach ($items as $item) {
            // Process item
            sleep(0.1);
            $progressBar->advance();
        }
    });

    return self::SUCCESS;
}

Error Handling

protected function execute(InputInterface $input, OutputInterface $output): int
{
    try {
        // Risky operation
        $result = $this->performOperation();
        
        if (!$result) {
            $this->warning('Operation completed with warnings');
            return self::SUCCESS;
        }
        
        $this->success('Operation completed successfully');
        return self::SUCCESS;
    } catch (ValidationException $e) {
        $this->error('Validation failed: ' . $e->getMessage());
        return self::INVALID;
    } catch (\Exception $e) {
        $this->error('Unexpected error: ' . $e->getMessage());
        
        if ($input->getOption('verbose')) {
            $this->line($e->getTraceAsString());
        }
        
        return self::FAILURE;
    }
}

Service Integration

class MyCommand extends BaseCommand
{
    private MyService $myService;
    private DatabaseInterface $database;

    public function __construct()
    {
        parent::__construct();
        
        // Resolve services from DI container
        $this->myService = $this->getService(MyService::class);
        $this->database = $this->getService(DatabaseInterface::class);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // Use services
        $users = $this->database->select('users')->get();
        $result = $this->myService->processUsers($users);

        return self::SUCCESS;
    }
}

Configuration and Environment

protected function execute(InputInterface $input, OutputInterface $output): int
{
    // Check environment
    if ($this->isProduction() && !$input->getOption('force')) {
        if (!$this->confirmProduction('perform this operation')) {
            return self::FAILURE;
        }
    }

    // Access configuration
    $timeout = config('app.timeout', 30);
    $debug = config('app.debug', false);

    return self::SUCCESS;
}

This comprehensive console system provides powerful tools for application management, development workflows, and system administration while maintaining consistency, safety, and ease of use.