DALT.PHP
Advanced

Framework Architecture

Understanding DALT.PHP's internal structure

Framework Architecture

DALT.PHP is built with simplicity and readability in mind. Every component fits in one file and can be understood by reading the code.

Design Principles

  1. Simplicity First - No magic, no hidden abstractions
  2. One File Per Component - Easy to locate and understand
  3. Explicit Over Implicit - Clear, traceable code flow
  4. Educational Focus - Designed for learning, not production

Core Components

Router (framework/Core/Router.php)

Maps URLs to controllers using regex pattern matching.

class Router {
    protected array $routes = [];
    
    public function get($uri, $controller) {
        $this->routes['GET'][$uri] = $controller;
        return $this;
    }
    
    public function route($uri, $method) {
        foreach ($this->routes[$method] as $route => $controller) {
            if ($this->matchUri($route, $uri)) {
                // Extract parameters and execute controller
            }
        }
        abort(404);
    }
}

Key Features:

  • Pattern matching with {parameter} syntax
  • Parameter extraction into $_GET
  • Middleware support via only() method
  • HTTP method routing (GET, POST, PATCH, DELETE)

Database (framework/Core/Database.php)

PDO wrapper with query builder and prepared statements.

class Database {
    protected PDO $connection;
    protected PDOStatement $statement;
    
    public function query($query, $params = []) {
        $this->statement = $this->connection->prepare($query);
        $this->statement->execute($params);
        return $this;
    }
    
    public function find() {
        return $this->statement->fetch();
    }
    
    public function get() {
        return $this->statement->fetchAll();
    }
}

Key Features:

  • Prepared statements for SQL injection prevention
  • Method chaining for clean syntax
  • Support for SQLite and PostgreSQL
  • findOrFail() for automatic 404 handling

Authenticator (framework/Core/Authenticator.php)

Handles user authentication and session management.

class Authenticator {
    public function attempt($email, $password) {
        $user = $this->findUser($email);
        
        if ($user && password_verify($password, $user['password'])) {
            $this->login($user);
            return true;
        }
        return false;
    }
    
    public function login($user) {
        $_SESSION['user'] = [
            'email' => $user['email']
        ];
        session_regenerate_id(true);
    }
    
    public function logout() {
        Session::destroy();
    }
}

Key Features:

  • Secure password verification with password_verify()
  • Session regeneration for security
  • Simple login/logout flow

Session (framework/Core/Session.php)

Session management with flash data support.

class Session {
    public static function put($key, $value) {
        $_SESSION[$key] = $value;
    }
    
    public static function get($key, $default = null) {
        return $_SESSION[$key] ?? $_SESSION['_flash'][$key] ?? $default;
    }
    
    public static function flash($key, $value) {
        $_SESSION['_flash'][$key] = $value;
    }
    
    public static function unflash() {
        unset($_SESSION['_flash']);
    }
}

Key Features:

  • Flash data for one-time messages
  • Automatic cleanup after next request
  • Simple key-value storage

Container (framework/Core/Container.php)

Dependency injection container for service management.

class Container {
    protected array $bindings = [];
    
    public function bind($key, $resolver) {
        $this->bindings[$key] = $resolver;
    }
    
    public function resolve($key) {
        if (!isset($this->bindings[$key])) {
            throw new Exception("No binding found for {$key}");
        }
        
        $resolver = $this->bindings[$key];
        return call_user_func($resolver);
    }
}

Key Features:

  • Service registration with bind()
  • Lazy resolution with resolve()
  • Singleton pattern support

Middleware System

Middleware Resolver

class Middleware {
    const MAP = [
        'auth' => Auth::class,
        'guest' => Guest::class,
        'csrf' => Csrf::class,
    ];
    
    public static function resolve($keys) {
        foreach ($keys as $key) {
            $middleware = static::MAP[$key];
            (new $middleware)->handle();
        }
    }
}

Auth Middleware

class Auth {
    public function handle() {
        if (!isset($_SESSION['user'])) {
            redirect('/login');
        }
    }
}

CSRF Middleware

class Csrf {
    public function handle() {
        $token = $_POST['_token'] ?? '';
        $sessionToken = $_SESSION['_token'] ?? '';
        
        if (!hash_equals($sessionToken, $token)) {
            abort(403);
        }
    }
}

Request Flow Diagram

HTTP Request

public/index.php (Front Controller)
    ├─ Start session
    ├─ Load helpers
    └─ Bootstrap framework

framework/Core/bootstrap.php
    ├─ Load .env
    ├─ Load config
    ├─ Create container
    └─ Bind database

Router
    ├─ Load routes
    ├─ Match URI
    └─ Extract parameters

Middleware Pipeline
    ├─ Auth check
    ├─ CSRF validation
    └─ Custom middleware

Controller
    ├─ Business logic
    ├─ Database queries
    └─ Validation

View
    ├─ PHP template
    ├─ Vue components
    └─ Tailwind CSS

HTTP Response

Helper Functions

Located in framework/Core/functions.php:

// Dump and die
function dd($value) {
    echo '<pre>';
    var_dump($value);
    echo '</pre>';
    die();
}

// Render view
function view($path, $attributes = []) {
    extract($attributes);
    require base_path('resources/views/' . $path);
}

// Redirect
function redirect($path) {
    header("Location: {$path}");
    exit();
}

// Abort with status
function abort($code = 404) {
    http_response_code($code);
    require base_path("resources/views/{$code}.view.php");
    die();
}

// Get base path
function base_path($path = '') {
    return BASE_PATH . '/' . $path;
}

Configuration

Application Config

// config/app.php
return [
    'name' => env('APP_NAME', 'DALT.PHP'),
    'env' => env('APP_ENV', 'local'),
    'debug' => env('APP_DEBUG', true),
    'url' => env('APP_URL', 'http://localhost:8000'),
];

Database Config

// config/database.php
return [
    'connection' => env('DB_CONNECTION', 'sqlite'),
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', 3306),
    'database' => env('DB_DATABASE', 'database/database.sqlite'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
];

Stability Guidelines

Parts That MUST Remain Stable

These are the debugging targets - don't refactor them:

  • ✅ Router.php - Route matching logic
  • ✅ Middleware system - Execution order
  • ✅ Database.php - Query execution
  • ✅ Session.php - Flash data handling
  • ✅ Authenticator.php - Login/logout flow
  • ✅ Request lifecycle - Entry to response

Parts That Can Be Modified

These can be enhanced without breaking challenges:

  • ✅ Helper functions - Add new helpers
  • ✅ Validator.php - Add validation rules
  • ✅ View templates - Improve UI/UX
  • ✅ Frontend stack - Vue components
  • ✅ Error pages - Enhance 403/404/500
  • ✅ Configuration - Add new options

Important: The core framework is intentionally simple for educational purposes. In production, use established frameworks like Laravel or Symfony.

Next Steps

On this page