PHPackages                             switch/controller - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. switch/controller

ActiveLibrary

switch/controller
=================

High-velocity base controller, request validation, middleware dispatching, and response helpers for the Switch Framework.

00PHP

Since Aug 14Pushed todayCompare

[ Source](https://github.com/celionatti/switch-controller)[ Packagist](https://packagist.org/packages/switch/controller)[ RSS](/packages/switch-controller/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

Switch Controller (`switch/controller`)
=======================================

[](#switch-controller-switchcontroller)

[![Latest Version](https://camo.githubusercontent.com/34e695c6016bc2a934a96bed696e29b2f2ab562a7134d65a55d00653cd506bea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75652e737667)](https://github.com/celionatti/switch-controller)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![PHP](https://camo.githubusercontent.com/d7583679f2fa23bc68186b2e772180e9fbd9afb79c983dff6b928e19d389aae8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e322d3737376262342e737667)](https://php.net)

**Switch Controller** provides the base controller architecture, high-speed request validation (with database `unique` / `exists` support), middleware management, JSON response builders, and Switch Live integration helpers for the **Switch Framework**.

---

⚡ Features
----------

[](#-features)

- 🎮 **Base Controller (`Controller`)**: View rendering, JSON responses, redirects, and Switch Live helpers.
- 🛡️ **Built-in Fast Validator**: 30+ rules including `unique`, `exists`, `email`, `between`, `digits`, `date`, `uuid`, `alpha_dash`, `nullable`, and custom closures.
- 🧩 **Controller-Level Middleware**: Register middleware with `only` / `except` filters.
- 🚀 **Switch Live Helpers**: Direct access to `toast()`, `emit()`, `liveRedirect()`, `target()`, `title()`, and `preserveScroll()`.
- 📦 **ResourceController Interface**: Standardized CRUD contract for API and web controllers.

---

📦 Installation
--------------

[](#-installation)

```
composer require switch/controller
```

---

🚀 Quick Usage
-------------

[](#-quick-usage)

### 1. Extending the Base Controller

[](#1-extending-the-base-controller)

```
namespace App\Controllers;

use Switch\Controller\Controller;
use Psr\Http\Message\ServerRequestInterface;
use App\Models\User;

class UserController extends Controller
{
    public function __construct()
    {
        // Register middleware on specific actions
        $this->middleware('AuthMiddleware', ['except' => ['index', 'show']]);
    }

    public function index()
    {
        return $this->view('users.index', [
            'users' => User::all()
        ]);
    }

    public function store(ServerRequestInterface $request)
    {
        // Fast Request Validation with Unique check
        $validated = $this->validate($request, [
            'name' => 'required|min:2|max:50',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6|confirmed',
            'role_id' => 'required|exists:roles,id',
            'bio' => 'nullable|max:500'
        ]);

        $user = User::create($validated);

        // Switch Live Toast Notification
        $this->toast("User {$user->name} created successfully!", 'success');

        return $this->redirect('/users');
    }

    public function update(ServerRequestInterface $request, int $id)
    {
        // Unique check ignoring current user ID
        $validated = $this->validate($request, [
            'email' => "required|email|unique:users,email,{$id},id",
            'name' => 'required|min:2'
        ]);

        User::findOrFail($id)->update($validated);
        $this->toast('User updated successfully!', 'success');

        return $this->redirect('/users');
    }

    public function apiIndex()
    {
        // Fast JSON Response
        return $this->json([
            'status' => 'success',
            'data' => User::all()
        ]);
    }
}
```

---

🛡️ Validation Rules Reference
-----------------------------

[](#️-validation-rules-reference)

### 🗄️ Database Rules

[](#️-database-rules)

RuleDescriptionExample`unique:table,column,exceptId,idColumn`Checks value is unique in table`'email' => 'unique:users,email'`
`'email' => 'unique:users,email,42,id'``exists:table,column`Checks value exists in table`'category_id' => 'exists:categories,id'`### 🔤 String &amp; Format Rules

[](#-string--format-rules)

RuleDescriptionExample`required`Must be present and non-empty`'name' => 'required'``nullable`Allows null/empty values`'bio' => 'nullable|max:500'``email`Must be a valid email`'email' => 'email'``url`Must be a valid URL`'website' => 'url'``ip` / `ipv4` / `ipv6`Valid IP address`'ip_address' => 'ipv4'``uuid`Valid UUID format`'device_id' => 'uuid'``json`Must be a valid JSON string`'payload' => 'json'``alpha`Letters only`'first_name' => 'alpha'``alpha_num`Letters and numbers only`'username' => 'alpha_num'``alpha_dash`Letters, numbers, dashes, underscores`'slug' => 'alpha_dash'``string`Must be a string`'title' => 'string'``boolean``true`, `false`, `1`, `0`, `'yes'`, `'no'``'is_active' => 'boolean'``accepted`Must be accepted (`yes`, `on`, `1`, `true`)`'terms' => 'accepted'``declined`Must be declined (`no`, `off`, `0`, `false`)`'opt_out' => 'declined'`### 📏 Size &amp; Range Rules

[](#-size--range-rules)

RuleDescriptionExample`min:val`Minimum string length / number / array count`'password' => 'min:8'``max:val`Maximum string length / number / array count`'summary' => 'max:200'``between:min,max`Value/length/count between min and max`'age' => 'between:18,65'``digits:N`Exact number of digits`'pin' => 'digits:4'``digits_between:min,max`Digits count in range`'card' => 'digits_between:13,19'``size:val`Exact length / value / count`'code' => 'size:6'``numeric`Must be numeric`'price' => 'numeric'``integer`Must be an integer`'quantity' => 'integer'``array`Must be a PHP array`'tags' => 'array'`### 📅 Date &amp; Time Rules

[](#-date--time-rules)

RuleDescriptionExample`date`Valid date string`'published_at' => 'date'``date_format:format`Exact date format`'dob' => 'date_format:Y-m-d'``before:date_or_field`Date must be before date/field`'start_date' => 'before:end_date'``after:date_or_field`Date must be after date/field`'end_date' => 'after:start_date'`### ⚖️ Comparison &amp; Equality Rules

[](#️-comparison--equality-rules)

RuleDescriptionExample`in:a,b,c`Must match one of allowed values`'role' => 'in:admin,editor,user'``not_in:a,b,c`Must not match disallowed values`'tier' => 'not_in:banned,suspended'``confirmed`Must match `{field}_confirmation``'password' => 'confirmed'``same:field`Must match another field`'new_email' => 'same:email_confirm'``different:field`Must differ from another field`'new_password' => 'different:old_password'``starts_with:a,b`Must start with one of prefixes`'url' => 'starts_with:http://,https://'``ends_with:a,b`Must end with one of suffixes`'file' => 'ends_with:.jpg,.png'``regex:/.../`Must match regex pattern`'code' => 'regex:/^[A-Z0-9]+$/'``not_regex:/.../`Must not match regex pattern`'username' => 'not_regex:/admin/i'`---

💡 Custom Rules &amp; Extensibility
----------------------------------

[](#-custom-rules--extensibility)

### Using Closures:

[](#using-closures)

```
$validated = $this->validate($request, [
    'promo_code' => [
        'required',
        fn($val) => $val === 'SWITCH2026' ? true : 'The promo code is expired or invalid.'
    ]
]);
```

### Global Custom Rules:

[](#global-custom-rules)

```
use Switch\Controller\Validation\Validator;

Validator::extend('phone', function ($field, $value) {
    return preg_match('/^\+?[1-9]\d{1,14}$/', (string) $value);
});

// Now available everywhere:
$this->validate($request, ['mobile' => 'required|phone']);
```

---

🧪 Testing
---------

[](#-testing)

```
composer test
```

---

📄 License
---------

[](#-license)

The Switch Controller package is open-source software licensed under the [MIT license](LICENSE).

###  Health Score

21

—

LowBetter than 17% of packages

Maintenance65

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/68065074?v=4)[Celio Natti](/maintainers/celionatti)[@celionatti](https://github.com/celionatti)

---

Top Contributors

[![celionatti](https://avatars.githubusercontent.com/u/68065074?v=4)](https://github.com/celionatti "celionatti (6 commits)")

### Embed Badge

![Health badge](/badges/switch-controller/health.svg)

```
[![Health](https://phpackages.com/badges/switch-controller/health.svg)](https://phpackages.com/packages/switch-controller)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
