Files
LightMVC/README.md
T

2.9 KiB
Executable File

LightMVC - Lightweight PHP MVC Framework

A minimal, PSR-4 compliant PHP MVC framework designed for simplicity and scalability.

Directory Structure

├── app/
│   ├── Controllers/  # Application logic (Controllers)
│   ├── Models/       # Data structures (Models)
│   └── Views/        # UI templates (Views)
├── core/             # Framework engine
│   ├── Application.php
│   ├── Controller.php
│   ├── Request.php
│   ├── Response.php
│   ├── Router.php
│   └── View.php
├── public/           # Entry point and static assets
│   ├── css/          # Custom CSS files
│   ├── js/           # Custom JS files
│   └── images/       # Static images
├── node_modules/     # Frontend dependencies
├── vendor/           # Composer dependencies

Asset Management & npm

This project uses npm for frontend dependencies (e.g., Bootstrap).

  1. Initialize/Install: npm install
  2. Add custom CSS/JS in public/css/app.css and public/js/app.js.
  3. Reference assets in app/Views/layouts/main.php.

How It Works

  1. Request Flow: Requests hit public/index.php.
  2. Initialization: Core\Application initializes Request, Response, Router, and View.
  3. Routing: The Router matches the Request path against registered routes.
  4. Dispatching: If a match is found, the Router instantiates the controller and invokes the requested method.
  5. Controller Action: The controller handles business logic and returns a View using $this->render().
  6. Response: View loads the layout from app/Views/layouts/main.php, injects the view content into the {{content}} placeholder, and returns the response.

Adding a New Route

In public/index.php, register a route mapping a path to a controller method:

$app->router->get('/path', [ControllerClass::class, 'methodName']);

API Routing

API routes are registered in public/index.php with the /api/ prefix to keep them separate from regular page routes.

Example API Route

$app->router->get('/api/ping', [App\Controllers\ApiController::class, 'ping']);

API Controller

The ApiController class lives in app/Controllers/ApiController.php and should contain methods for API endpoints.

Example:

<?php
namespace App\Controllers;

use Core\Controller;

class ApiController extends Controller
{
    public function ping()
    {
        // Simple health-check endpoint
        $this->response->setHeader('Content-Type', 'application/json');
        $this->response->setBody(json_encode(['status' => 'ok', 'time' => microtime(true)]));
    }
}

Testing the API

You can test the /api/ping endpoint with:

curl http://localhost/api/ping

Expected response:

{"status":"ok","time":1718409600.123}