enduron/core

Enduron light PHP Framework Core

Installs: 103

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Forks: 0

Type:enduron-core

pkg:composer/enduron/core

2.0.0 2025-11-12 12:14 UTC

This package is auto-updated.

Last update: 2025-11-14 07:37:26 UTC


README

PHP Version License Framework

Enduron Core is a lightweight, modern PHP framework designed for rapid web application development. It features a clean MVC architecture, powerful ORM capabilities, comprehensive migration system, and both HTTP and CLI kernel support.

🚀 Features

Core Framework

  • Modern PHP 8.2+ with strict typing and modern language features
  • PSR-4 Autoloading with Composer integration
  • Dual Kernel Architecture - HTTP for web requests, CLI for command-line operations
  • MVC Pattern with automatic routing and controller dispatch
  • Environment Configuration with .env file support
  • Built-in WebSocket Server for real-time communication and synchronization

Database & ORM

  • Powerful Query Builder with fluent interface and criteria support
  • Advanced ORM with automatic model generation and relationships
  • Alternative Database Connections per query for multi-database scenarios
  • Transaction Management with automatic rollback on errors
  • UUID Support with binary storage optimization

Migration System

  • Full Schema Management with up/down migrations
  • Data Seeding with batch operations and conditional logic
  • Migration Tracking with batch rollback capabilities
  • Schema Builder with fluent table creation syntax
  • Environment Awareness for different deployment scenarios

API Development

  • RESTful API Support with JSON/XML output formats
  • Token-based Authentication with automatic user tracking
  • CORS Handling for cross-origin requests
  • Request Validation and method restriction

Real-Time Features

  • WebSocket Server with process management (start/stop/status)
  • Real-time Sync Manager with automatic change broadcasting
  • Client Notifications for database changes (insert/update/delete)
  • Background Process Management with PID tracking and uptime monitoring

Performance & Monitoring

  • Built-in Caching with multiple backend support
  • Performance Monitoring in development mode
  • Query Timing and memory usage tracking
  • Debug Headers for development insights

📋 Requirements

  • PHP 8.2 or higher
  • PDO MySQL Extension
  • Sockets Extension (ext-sockets) - Required for WebSocket server
  • Composer for dependency management

Recommended Extensions

  • ext-apcu - For APCu cache backend
  • ext-fileinfo - For file type detection
  • ext-gd - For image processing
  • ext-mysqli - Alternative database connection
  • ext-openssl - For security features
  • ext-zip - For archive handling
  • ext-zlib - For compression

🛠 Installation

Via Composer

composer require enduron/core

After installation, the framework will automatically:

  • Create required directory structure (application/, storage/, etc.)
  • Copy configuration templates to application/config/
  • Copy core migrations to application/migrations/
  • Create example job files for the scheduler

Important: Run migrations after installation to set up internal tables:

php enduron migrate:up

Manual Installation

  1. Clone the repository:

    git clone https://github.com/your-username/enduron-core.git
    cd enduron-core
    
  2. Install dependencies:

    composer install
    

The post-install-cmd hook will automatically set up the application structure.

  1. Set up your environment:

    cp .env.example .env
    # Edit .env with your database credentials
    
  2. Run initial migrations:

    php enduron migrate:up
    

🔄 Upgrading

When upgrading to a new version of Enduron Core:

composer update enduron/core

The post-update-cmd hook will automatically:

  • Update configuration templates (with backup of existing configs)
  • Copy/update core migrations
  • Automatically run migrations to update internal database tables
  • Preserve your existing application code and configurations

Manual Migration After Upgrade

If automatic migrations fail or you prefer manual control:

# Check migration status
php enduron migrate:status

# Run pending migrations
php enduron migrate:up

# Rollback if needed
php enduron migrate:rollback --steps=1

Version Compatibility

Enduron Core follows semantic versioning:

  • Major version (1.x → 2.x): Breaking changes, manual migration required
  • Minor version (1.1 → 1.2): New features, backward compatible
  • Patch version (1.1.0 → 1.1.1): Bug fixes, fully compatible

⚙️ Configuration

Environment Variables

Create a .env file in your project root:

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password

# Application Environment
APP_ENV=development

# ORM Compiler Settings
ORMCOMPILER_HAS_UUID=true

Application Configuration

Create application/config/app.php:

<?php
return [
    'name' => 'Your Application Name',
    'version' => '1.0.0',
    'timezone' => 'Europe/Berlin',
    // Additional configuration...
];

Routing Configuration

Create application/config/route.php:

<?php
return [
    'api' => 'api/index',
    'admin' => 'admin/dashboard',
    'users/(\d+)' => 'user/show',
    // Additional routes...
];

🚦 Quick Start

1. Basic Application Setup

<?php
// public/index.php
require_once '../vendor/autoload.php';

use Enduron\Core\EnduronCore;

$app = new EnduronCore(__DIR__ . '/..');
$app->run(EnduronCore::KERNEL_MODE_HTTP);

2. Creating a Controller

<?php
// application/controller/UserController.php
namespace Enduron\HTTP\Controller;

use Enduron\Core\Controller\BaseController;

class UserController extends BaseController
{
    public function index()
    {
        $users = UserQuery::create()->find();
        return $this->view->render('user/index', ['users' => $users]);
    }

    public function show(User $user)
    {
        return $this->view->render('user/show', ['user' => $user]);
    }
}

3. Database Migrations

Create a migration:

php enduron migrate:make CreateUsersTable

Define the migration:

<?php
use Enduron\Core\Migration\BaseMigration;
use Enduron\Core\Migration\MigrationSchema;

class CreateUsersTable extends BaseMigration
{
    public function up(): void
    {
        $this->createTable('users', function(MigrationSchema $table) {
            $table->uuid();
            $table->string('name');
            $table->string('email')->unique();
            $table->boolean('active')->default(true);
            $table->timestamps();
            $table->userTracking();
        });

        // Seed initial data
        $this->insert('users', [
            'uid' => $this->generateUuid(),
            'name' => 'Admin User',
            'email' => 'admin@example.com',
            'active' => true,
            'tstamp_created' => $this->now()
        ]);
    }

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

Run migrations:

php enduron migrate:up

4. Using the Query Builder

<?php
// Basic queries
$users = UserQuery::create()
    ->where('active', true)
    ->orderBy('name')
    ->find();

// Complex queries with joins
$users = UserQuery::create()
    ->addJoin(ProfileQuery::create(), 'INNER')
    ->where('users.active', true)
    ->where('profiles.verified', true)
    ->find();

// Alternative database connection
$remoteConnection = new PDO('mysql:host=remote.db;dbname=backup', $user, $pass);
$backupUsers = UserQuery::create()
    ->useConnection($remoteConnection)
    ->find();

5. API Development

<?php
// application/controller/ApiUserController.php
namespace Enduron\HTTP\Controller;

use Enduron\Core\Api\ApiBaseController;

class ApiUserController extends ApiBaseController
{
    public function index()
    {
        $users = UserQuery::create()->active()->find();
        return $this->sendSuccess($users->toArray());
    }

    public function show(User $user)
    {
        if (!$user) {
            return $this->sendError('User not found', 404);
        }

        return $this->sendSuccess($user->toArray());
    }
}

📚 Advanced Usage

Custom Database Connections

<?php
// Use different database for specific queries
$analyticsDB = new PDO('mysql:host=analytics.db;dbname=stats', $user, $pass);

$stats = AnalyticsQuery::create()
    ->useConnection($analyticsDB)
    ->where('date', '>=', '2024-01-01')
    ->find();

Data Seeding

<?php
// application/seeders/UserSeeder.php
class UserSeeder extends Seeder
{
    public function run(): void
    {
        $this->whenEmpty('users', function($seeder) {
            $seeder->insertBatch('users', [
                [
                    'uid' => $seeder->uuid(),
                    'name' => 'John Doe',
                    'email' => 'john@example.com',
                    'active' => true
                ],
                [
                    'uid' => $seeder->uuid(),
                    'name' => 'Jane Smith',
                    'email' => 'jane@example.com',
                    'active' => true
                ]
            ]);
        });
    }
}

Command Line Interface

# Migration commands
php enduron migrate:up              # Run pending migrations
php enduron migrate:down            # Rollback last batch
php enduron migrate:rollback --steps=3  # Rollback 3 batches
php enduron migrate:status          # Show migration status
php enduron migrate:make CreateTable    # Create new migration

# WebSocket Server commands
php enduron websocket start         # Start WebSocket server in background
php enduron websocket stop          # Stop running WebSocket server
php enduron websocket status        # Show server status (PID, uptime, etc.)
php enduron websocket run           # Run server in foreground (blocking)
php enduron websocket log           # Show last 50 lines of log
php enduron websocket log 100       # Show last 100 lines of log
php enduron websocket log:follow    # Follow log in real-time (like tail -f)
php enduron websocket clear-log     # Clear log file

# Framework commands
php enduron cache:clear             # Clear application cache
php enduron ormcompiler:run         # Generate ORM classes
php enduron help                    # Show all commands

WebSocket Server Management

Enduron Core includes a built-in WebSocket server for real-time communication and synchronization. The WebSocket server integrates with the SyncManager to push database changes to connected clients in real-time.

Starting the WebSocket Server:

# Start in background (recommended for production)
php enduron websocket start

# Check if server is running
php enduron websocket status

# Output:
# WebSocket Server Status
# =======================
# Status:       RUNNING
# PID:          12345
# Process:      php enduron websocket run
# Uptime:       2h 15m 30s

Managing the Server:

# Stop the server
php enduron websocket stop

# View server logs
php enduron websocket log

# Follow logs in real-time (useful for debugging)
php enduron websocket log:follow

# Clear old logs
php enduron websocket clear-log

Running in Foreground (Development):

# Run server in foreground (blocks terminal)
php enduron websocket run

Production Deployment:

For production environments, use a process manager like systemd or supervisor to ensure the WebSocket server restarts automatically:

# /etc/supervisor/conf.d/enduron-websocket.conf
[program:enduron-websocket]
command=/usr/bin/php /var/www/html/enduron websocket run
directory=/var/www/html
user=www-data
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/enduron-websocket.log

Client Connection:

Connect to the WebSocket server from JavaScript:

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
    console.log('Connected to WebSocket server');
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Sync update:', data);
    // Handle real-time updates: data.tablename, data.target_id, data.status
};

Automatic Core Migrations

Enduron Core manages its own internal database tables (like sync_status) through automatic migrations that run during Composer operations:

During Installation (composer install):

  • Core migrations are copied from vendor/enduron/core/templates/application/migrations/ to application/migrations/
  • You should run php enduron migrate:up manually after installation

During Updates (composer update):

  • Core migrations are automatically updated to the latest version
  • Migrations are automatically executed to update internal tables
  • No manual intervention required - your database schema stays current

Core Tables Managed by Enduron:

  • sync_status - Real-time synchronization tracking (MEMORY engine)
  • scheduler_runs - Task scheduler execution logs
  • migrations - Migration tracking table

If a core migration fails during composer update, you can run it manually:

php enduron migrate:up

Fallback Mechanism: If migrations haven't been executed yet, Enduron will automatically create required tables when first accessed. However, using the migration system ensures your schema is always properly versioned and up-to-date.

Performance Monitoring

When APP_ENV=development, the framework provides detailed performance metrics:

Enduron-Memory-Usage: 2.5 mb
Enduron-Runtime: 0.0234 sec
Enduron-DB-Queries: 12.34 ms

🏗 Architecture

Directory Structure

project/
├── application/
│   ├── config/           # Configuration files
│   ├── controller/       # Application controllers
│   ├── migrations/       # Database migrations
│   ├── seeders/         # Data seeders
│   └── views/           # Template files
├── public/              # Web accessible files
│   └── index.php        # Application entry point
├── vendor/              # Composer dependencies
├── Classes/             # Enduron Core framework files
├── .env                 # Environment configuration
└── composer.json        # Dependencies and autoloading

Core Components

  • EnduronCore: Main application class and bootstrapper
  • HttpKernel: Web request handling and routing
  • CmdKernel: Command-line interface and task runner
  • BaseQuery: Fluent query builder with criteria support
  • BaseObject: ORM base class with automatic tracking
  • BaseMigration: Database migration and seeding system
  • ApiBaseController: RESTful API development base

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Development Guidelines

  • Follow PSR-12 coding standards
  • Write comprehensive tests for new features
  • Update documentation for API changes
  • Use semantic versioning for releases

📖 Documentation

🔒 Security

Reporting Security Vulnerabilities

Please report security vulnerabilities privately to security@enduron.dev.

Security Features

  • Automatic SQL injection prevention with prepared statements
  • CSRF protection (when implemented in application layer)
  • Input sanitization and validation helpers
  • Secure session management
  • Environment-based configuration separation

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Built with modern PHP 8.2+ features
  • Inspired by Laravel, Symfony, and other modern frameworks
  • Thanks to all contributors and the PHP community

📞 Support

Happy Coding with Enduron Core! 🚀