Introduction

Welcome to Slenix — a PHP framework that values simplicity, clarity, and developer joy. Whether you're building a REST API, a full-stack web application, or a lightweight microservice, Slenix gives you exactly the tools you need and nothing you don't.

What is Slenix?

Slenix is a lightweight, zero-dependency PHP framework built for developers who want full control over their application without the overhead of large, opinionated stacks. It ships with a fast regex-based router, the Luna template engine, fluent session and flash management, automatic CSRF protection, JWT authentication, a built-in ORM, database migrations, seeders, an HTTP client, a mail sender, and a rich library of global helpers — all implemented in native PHP with no Composer runtime packages required.

The entire framework can be read and understood in a single afternoon. There are no hidden layers, no magic containers, no gigabytes of vendor code.

See how simple it is to define a route that fetches a user by ID:

php
use Slenix\Http\Routing\Router;
use Slenix\Http\Request;
use Slenix\Http\Response;

Router::get('/users/{id}', function (Request $req, Response $res, int $id) {
    $user = User::find($id);

    if (!$user) {
        return $res->status(404)->json(['error' => 'User not found.']);
    }

    return view('users.profile', compact('user'));
});

When /users/42 is accessed, Slenix resolves the route, injects the typed Request and Response objects, and passes the {id} parameter directly to your handler. If the user is not found, a structured 404 JSON response is returned automatically.


Simple and Expressive Routing

With Slenix, defining routes is straightforward. Use Router::get(), Router::post(), and the other HTTP verbs to register routes in routes/web.php. Routes support named parameters, middleware, groups, and named URL generation:

php
// Named route with parameter
Router::get('/hello/{name}', function (Request $req, Response $res, string $name) {
    $res->write("Hello, {$name}!");
})->name('hello');

// Generate URL from route name
$url = route('hello', ['name' => 'Cláudio']); // /hello/Cláudio

Discover how routing in Slenix gives you total control over your application's URL structure with a clean, readable syntax.


Powerful Middleware

Middleware in Slenix allows you to inspect, filter, and transform HTTP requests before they reach their final handler. This is the right place for authentication checks, rate limiting, request logging, and any cross-cutting concern you want applied consistently across multiple routes:

php
// Define a middleware
$ensureAuthenticated = function (Request $req, Response $res, callable $next) {
    if (!session()->has('user_id')) {
        return redirect('/login')->with('error', 'Please log in first.');
    }
    $next();
};

// Apply to a group of routes
Router::group('/dashboard', function () {
    Router::get('/',       [DashboardController::class, 'index']);
    Router::get('/users',  [DashboardController::class, 'users']);
})->middleware($ensureAuthenticated);

Learn more about how middleware in Slenix lets you build reusable, composable request pipelines.


Luna — Template Engine

Slenix ships with Luna, a Blade-inspired template engine. Luna compiles .luna.php files to plain PHP, caches them on disk, and invalidates the cache automatically when the source file changes.

html
@extends('layouts.app')

@section('title', 'Dashboard')

@section('content')
    <h1>Welcome, {{ $user->name }}</h1>

    @forelse ($posts as $post)
        <article>
            <h2>{{ $post->title }}</h2>
            <p>{{ $post->excerpt }}</p>
            <a href="{{ route('posts.show', ['id' => $post->id]) }}">Read more</a>
        </article>
    @empty
        <p>No posts yet.</p>
    @endforelse
@endsection

Luna supports layouts, sections, includes, components, and all the directives you would expect — @if, @foreach, @csrf, @error, @old, @auth, and more. Read more in the Luna documentation.


Database and ORM

Slenix includes a full Active Record ORM and a fluent QueryBuilder that work with MySQL and PostgreSQL out of the box. Configure your connection in .env and start querying immediately:

dotenv
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=my_database
DB_USERNAME=root
DB_PASSWORD=secret
DB_CHARSET=utf8mb4

Define a model and use it anywhere in your application:

php
namespace App\Models;

use Slenix\Supports\Database\Model;

class Post extends Model
{
    protected array $fillable = ['title', 'body', 'user_id'];
    protected array $casts    = ['published_at' => 'datetime'];

    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

// Querying
$posts = Post::where('status', 'published')
             ->with('author')
             ->orderBy('published_at', 'DESC')
             ->paginate(10, $page);

Slenix models support relationships (hasOne, hasMany, belongsTo, belongsToMany), soft deletes, automatic slug generation, hooks, eager loading, and much more. Explore the full database documentation.


Database Migrations

Slenix includes a first-class migration system that keeps your database schema under version control. Define your tables once using the fluent Blueprint API and let Celestial manage the rest:

php
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name', 150);
            $table->string('slug')->unique();
            $table->text('description')->nullable();
            $table->decimal('price', 10, 2);
            $table->integer('stock')->default(0);
            $table->boolean('is_active')->default(true);
            $table->foreignId('category_id')->constrained()->onDelete('cascade');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Migrations are managed entirely through the Celestial CLI — create, run, roll back, and inspect your schema history without touching raw SQL:

bash
php celestial make:migration create_products_table  # generates a timestamped file
php celestial migrate                               # runs all pending migrations
php celestial migrate:status                        # shows Ran / Pending for each file
php celestial migrate:rollback                      # reverts the last batch
php celestial migrate:fresh                         # drops everything and re-runs

Read the full migrations documentation to learn about all available column types, modifiers, indexes, and foreign key constraints.


Security Built In

Security is not an afterthought in Slenix — it is built into the framework core. CSRF protection is active automatically for every mutating request. All forms need just one directive:

html
<form action="{{ route('login') }}" method="post">
    @csrf
    <input type="email" name="email" value="{{ old('email') }}">
    <input type="password" name="password">
    <button type="submit">Log in</button>
</form>

For API routes, Slenix includes built-in JWT authentication. Generate a secret and protect entire route groups with a single middleware:

php
Router::group(['prefix' => '/api/v1', 'middleware' => ['jwt']], function () {
    Router::get('/me',     [UserController::class, 'profile']);
    Router::put('/me',     [UserController::class, 'update']);
    Router::delete('/me',  [UserController::class, 'destroy']);
});

Learn about CSRF protection and JWT authentication in the security section of the documentation.


Helpers and Utilities

Slenix provides a comprehensive set of global helper functions available everywhere in your application — no imports needed:

php
// Redirects with flash data
redirect('/dashboard')->with('success', 'Profile saved!');
redirect()->back()->withErrors(['email' => 'Already taken.'])->withInput();

// Session
session()->put('cart', $items);
$cart = session()->get('cart', []);

// Flash messages
flash()->success('Saved!');
flash()->error('Something went wrong.');

// URLs
url('/users', ['page' => 2]);     // http://myapp.com/users?page=2
route('users.show', ['id' => 1]); // /users/1
asset('css/app.css');             // http://myapp.com/css/app.css

// Security
encrypt('sensitive data');
hash_make('password');
hash_check('password', $hash);

// Debug
dd($user);
dump($array);

The Str class adds 80+ string utilities for slug generation, case conversion, masking, and safe token creation. Read the full helpers reference.


Ready to Start?

Slenix gives you a framework that combines clarity and capability — ideal for projects of any size. Install it in under a minute and start building:

bash
composer create-project slenix/slenix my-app
cd my-app
php celestial serve

Your application is live at http://127.0.0.1:8080. Open routes/web.php and write your first route.

Explore the full documentation to learn everything Slenix has to offer — routing, templates, database, migrations, authentication, file uploads, email, HTTP client, and the Celestial CLI.