CLI Commands
Powerful command-line tools for Khadem framework development and deployment.
Getting Started
bash
# Install Khadem CLI globally
dart pub global activate khadem_cli
# Verify installation
khadem --version
# View help
khadem --help
# View available commands
khadem
Available Commands
- Project Management:
khadem new
- Create new projects - Development:
khadem serve
- Hot reload development server - Code Generation:
khadem make:*
- Generate models, controllers, etc. - Build & Deploy:
khadem build
- Production builds with multiple options - Database:
khadem migrate
,khadem db:seed
(coming soon) - Queue:
khadem queue:work
(coming soon) - Custom Commands: Automatically discovered from
lib/app/commands/
directory
✨ Auto-Discovery: Custom commands are automatically discovered using Dart mirrors - no manual registration required!
Project Management
bash
# Create a new Khadem project
khadem new --name=my_project
# Create project with specific name
khadem new --name=my_api
# List available templates (if any)
khadem new --help
# Initialize project in existing directory (if supported)
# khadem init (not currently available)
Project Creation Features
- Uses
khadem_template
as base - Automatic placeholder replacement
- JWT secret key auto-generation
- Project name validation
- Environment file configuration
Project Structure
--name
- Required project name- Automatic folder structure creation
- Dependency installation ready
- Pre-configured with best practices
Development Server
bash
# Start development server with hot reload
khadem serve
# Start server on specific port
khadem serve --port=3001
# Start server with file watching disabled
khadem serve --watch=false
# Interactive commands during development:
# r - Hot reload (reload code changes)
# f - Hot restart (full application restart)
# c - Clear consecutive failure count
# q - Quit server
# VM Service will be available on port 8181 for debugging
Advanced Server Features
- VM Service Integration: Hot reload and restart via Dart VM
- File Watching: Automatic detection of Dart file changes
- Interactive Controls: Keyboard shortcuts during development
- Error Recovery: Automatic restart on compilation errors
- Custom Port: Configurable server port
- Debounced Reloads: Prevents excessive reloads during rapid changes
- Process Management: Proper cleanup and signal handling
Code Generation
bash
# Generate a model
khadem make:model --name=User
# Generate model with folder structure
khadem make:model --name=Auth/User
# Generate controller
khadem make:controller --name=UserController
# Generate controller with folder
khadem make:controller --name=auth/AuthController
# Generate middleware
khadem make:middleware --name=AuthMiddleware
# Generate provider
khadem make:provider --name=AuthServiceProvider
# Generate job
khadem make:job --name=SendEmailJob
# Generate listener
khadem make:listener --name=UserEventListener
# Generate migration
khadem make:migration --name=create_users_table
Generated Components
- Models with relationships and traits
- Controllers with basic CRUD methods
- Middleware classes
- Service providers
- Job classes for queue processing
- Event listeners
- Database migrations
Generation Options
--name
- Component name (required)- Folder structure support (e.g., Auth/User)
- Automatic file placement
- Basic code stubs with comments
Database Operations
bash
# Database commands (currently disabled but implemented)
# These commands exist in the codebase but are commented out
# Migration commands (when enabled):
# khadem migrate - Run all pending migrations
# khadem migrate --reset - Rollback and re-run all migrations
# khadem migrate --fresh - Drop all tables and re-run migrations
# khadem migrate --status - Show migration status
# khadem migrate --force - Run in production (dangerous)
# khadem migrate --step=5 - Run migrations in batches
# khadem migrate --verbose - Detailed migration information
# Seeder commands (when enabled):
# khadem db:seed - Run all seeders
# khadem db:seed --class=UserSeeder - Run specific seeder
# khadem db:seed --force - Run in production
# khadem db:seed --verbose - Detailed seeder information
# For now, manage database manually or use direct SQL queries
Database Commands (Available but Disabled)
- Migration System: Full migration framework with Dart mirrors
- Auto-Discovery: Automatic migration file discovery and loading
- Production Safety: Force flags and confirmation prompts
- Seeder Support: Database seeding with mirror-based discovery
- Status Tracking: Migration status and rollback capabilities
- Batch Operations: Step-by-step and reset operations
Note: Database commands are implemented but currently disabled in the CLI registry. They will be enabled in a future release with full testing and documentation.
Testing & Quality
bash
# Run all tests (using pub run test)
dart test
# Run specific test file
dart test test/unit/user_test.dart
# Run tests with coverage
dart test --coverage
# Run tests in verbose mode
dart test --verbose
# Run tests matching pattern
dart test -k "User"
# Generate test coverage report
dart test --coverage && genhtml coverage/lcov.info -o coverage/html
# Run integration tests
dart test test/integration/
# Run performance tests
dart test test/performance/
# Generate test file (manual creation recommended)
# No automated test generation command available
Testing Tools
- Dart's built-in test runner
- Unit tests for individual functions
- Integration tests for components
- Coverage reporting with lcov
- Test file organization in test/ directory
Quality Tools
dart analyze
- Static analysisdart format
- Code formatting- Manual test coverage generation
- Dependency checking with pub
Deployment & Build
bash
# Generate Docker setup for production deployment (default)
khadem build
# Generate Docker setup with specific services
khadem build --services=mysql,redis,nginx
# Generate Docker setup with verbose logging
khadem build --verbose
# Generate Docker setup without deleting temp files
khadem build --delete-temp=false
# Available service options:
# - mysql: MySQL database service
# - postgres: PostgreSQL database service
# - mongo: MongoDB database service
# - redis: Redis cache service
# - nginx: Nginx reverse proxy
# After running khadem build:
# 1. Dockerfile and docker-compose.yml will be generated
# 2. .env.example template will be created
# 3. .dockerignore file will be generated
# 4. Copy .env.example to .env and configure your environment
# 5. Run: docker-compose up -d
Build Features
- Docker Generation: Automatically creates Dockerfile and docker-compose.yml
- Multi-Service Support: MySQL, PostgreSQL, MongoDB, Redis, Nginx
- Environment Templates: Auto-generates .env.example and .dockerignore
- Production Ready: Optimized Docker configurations with health checks
- Cross-Platform: Works on Linux, Windows, macOS via Docker
- Service Configuration: Flexible external service integration
Advanced Commands
bash
# Queue worker (currently disabled but implemented)
# khadem queue:work - Start processing queued jobs
# khadem queue:work --max-jobs=100 - Process max 100 jobs
# khadem queue:work --delay=2 - 2 second delay between jobs
# khadem queue:work --timeout=3600 - Stop after 1 hour
# Cache management (not implemented yet)
# khadem cache:clear (planned)
# Additional available commands:
# khadem build - Generate Docker setup for deployment
# khadem make:* - Code generation commands
# khadem new - Project creation
# khadem serve - Development server
Queue Management (Available but Disabled)
- Mirror-based Discovery: Auto-discover job classes using Dart mirrors
- Registry Support: Load jobs from lib/app/jobs/jobs.dart registry
- Background Processing: Process jobs asynchronously
- Job Limits: Configurable max jobs and timeouts
- Signal Handling: Graceful shutdown with Ctrl+C
- Error Recovery: Continue processing on individual job failures
Cache Operations
- Clear application cache
- Cache management for performance
- Memory and storage cache clearing
Configuration
bash
# View help for any command
khadem --help
khadem <command> --help
# Check system status (manual)
# No automated doctor command available
# Manual system checks:
# - Verify Dart SDK: dart --version
# - Check dependencies: dart pub get
# - Test database: manual verification
# Environment configuration (manual)
# Edit .env file directly for configuration
# No automated env generation command available
Environment Management
- Manual .env file configuration
- Automatic JWT secret generation
- Project-specific environment setup
- Configuration validation through code
Interactive Mode
bash
# Interactive development with serve command
khadem serve
# During development, use these keyboard shortcuts:
# r - Hot reload (reload code changes)
# f - Hot restart (full application restart)
# c - Clear consecutive failure count
# q - Quit the development server
# Manual code generation (no interactive mode available)
khadem make:model --name=User
khadem make:controller --name=UserController
khadem make:migration --name=create_users_table
Interactive Features
- Development server with keyboard controls
- Hot reload and restart during development
- Real-time file watching
- Interactive error feedback
- Manual code generation commands
Custom Commands
🎯 Automatic Command Discovery
Khadem automatically discovers and registers custom commands using Dart mirrors. Simply create your command class in the lib/app/commands/
directory, and it will be automatically available in the CLI without any manual registration required!
dart
// File: lib/app/commands/my_custom_command.dart
import 'dart:io';
import 'package:khadem/src/cli/bus/command.dart';
class MyCustomCommand extends KhademCommand {
@override
String get name => 'custom:example';
@override
String get description => 'Example custom command with auto-discovery';
// Flexible constructor - supports multiple patterns for auto-discovery
MyCustomCommand({Logger? logger}) : super(logger: logger ?? Logger()) {
argParser.addOption('name', abbr: 'n', help: 'Name argument');
argParser.addFlag('verbose', abbr: 'v', help: 'Verbose output');
}
@override
Future<void> handle(List<String> args) async {
final name = argResults?['name'] as String? ?? 'World';
final verbose = argResults?['verbose'] as bool? ?? false;
if (verbose) {
logger.info('🚀 Starting custom command...');
}
// Your custom logic here
logger.info('👋 Hello, $name!');
if (verbose) {
logger.info('✅ Custom command completed successfully.');
}
exit(0);
}
}
// No manual registration needed!
// Khadem automatically discovers and registers this command
// when placed in the lib/app/commands/ directory
Command Structure
- Inheritance from KhademCommand
- Argument and option definition
- Async handle method implementation
- Logger integration (flexible constructor support)
Auto-Discovery Features
- Mirror-based class discovery
- Cross-project compatibility
- Flexible constructor handling
- Package and file URI fallback
- Automatic registration
bash
# 1. Create your custom command file
# File: lib/app/commands/my_custom_command.dart
# (See example above)
# 2. Run khadem to see your command automatically discovered
khadem
# Output will show:
# Available commands:
# new Create a new Khadem project
# serve Start development server
# build Build application for deployment
# custom:example Example custom command with auto-discovery ← Your command!
# ...
# 3. Use your custom command
khadem custom:example --name=Developer --verbose
# Output:
# 🚀 Starting custom command...
# 👋 Hello, Developer!
# ✅ Custom command completed successfully.
# 4. Works across projects too!
# If you have Khadem in a different project (e.g., 'pingora'):
# Your commands will still be auto-discovered and available
How Auto-Discovery Works
- Khadem scans the
lib/app/commands/
directory for.dart
files - Uses Dart mirrors to load and inspect each file
- Identifies classes that extend
KhademCommand
- Automatically instantiates and registers discovered commands
- Supports both local project commands and cross-project usage
- Handles multiple constructor patterns (named parameters, positional, etc.)
Command Reference
Command | Description | Options |
---|---|---|
khadem new | Create a new Khadem project | --name |
khadem serve | Start development server with hot reload | --port, --watch |
khadem make:model | Generate a new model class | --name |
khadem make:controller | Generate a new controller class | --name |
khadem make:migration | Generate a new migration file | --name |
khadem make:middleware | Generate a new middleware class | --name |
khadem make:provider | Generate a new service provider | --name |
khadem make:job | Generate a new job class | --name |
khadem make:listener | Generate a new event listener | --name |
khadem build | Generate Docker setup for production deployment | --services, --verbose, --delete-temp |
custom:* | Custom commands auto-discovered from lib/app/commands/ | Varies by command |
Best Practices
✅ Do's
- Use descriptive names for generated components
- Run tests before deploying to production
- Use version control for all generated files
- Document custom CLI commands
- Use environment-specific configurations
- Regularly update CLI to latest version
- Use interactive mode for complex setups
- Backup database before manual database changes
- Use cache warming for better performance
- Test code generation output before using in production
- Follow Dart naming conventions for generated classes
- Place custom commands in the
lib/app/commands/
directory for auto-discovery - Use flexible constructor patterns for better compatibility
❌ Don'ts
- Don't use generic names for database tables
- Don't skip database backups before manual changes
- Don't hardcode sensitive data in commands
- Don't forget to clear cache after configuration changes
- Don't use development database for production testing
- Don't skip code generation tests
- Don't deploy without running the build command
- Don't modify generated code directly (use inheritance instead)
- Don't use the same port for multiple development servers
- Don't skip dependency installation after project creation
- Don't manually register custom commands (use auto-discovery instead)
- Don't place custom commands outside of
lib/app/commands/
directory
Troubleshooting
Common Issues
Command not found: Ensure Dart SDK is installed and khadem is activated globally
Port already in use: Use different port with
khadem serve --port=3001
Database connection failed: Check database configuration and connectivity
Build failures: Check for syntax errors with
dart analyze
Hot reload not working: Ensure VM service connection (check port 8181) and Dart files are being watched
Server crashes on startup: Check for syntax errors with
dart analyze lib/main.dart
Docker build issues: Check that Docker is installed and services are properly configured in .env
Custom command not discovered: Ensure command is in
lib/app/commands/
directory and extends KhademCommand
Mirror loading failed: Check that your command class has a compatible constructor (supports named or positional logger parameter)
bash
# Check CLI version and available commands
khadem --help
khadem <command> --help
# Check Dart SDK version
dart --version
# Install/update dependencies
dart pub get
# Check for syntax errors
dart analyze
# Run tests to verify functionality
dart test
# Clear any cached files (manual)
# Delete .dart_tool directory if needed
# rm -rf .dart_tool
# Check database connectivity (manual)
# Verify database configuration in config files
# View application logs (if running)
# tail -f logs/app.log (if log files exist)
# Restart development server
# Stop with Ctrl+C, then run: khadem serve
# Check custom command discovery
# Verify command file is in lib/app/commands/ directory
# Ensure command extends KhademCommand
# Check for syntax errors in command file