PHPackages                             codesaur/http-application - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. codesaur/http-application

ActiveLibrary[HTTP &amp; Networking](/categories/http)

codesaur/http-application
=========================

PSR-7 &amp; PSR-15 нийцсэн хөнгөн, уян хатан HTTP Application цөм

v7.0.0(1mo ago)11.0k↑100%1MITPHPCI passing

Since Mar 15Pushed today1 watchersCompare

[ Source](https://github.com/codesaur-php/HTTP-Application)[ Packagist](https://packagist.org/packages/codesaur/http-application)[ Docs](https://github.com/codesaur-php)[ RSS](/packages/codesaur-http-application/feed)WikiDiscussions main Synced yesterday

READMEChangelog (10)Dependencies (17)Versions (79)Used By (1)

codesaur/http-application
=========================

[](#codesaurhttp-application)

[![CI](https://github.com/codesaur-php/HTTP-Application/workflows/CI/badge.svg)](https://github.com/codesaur-php/HTTP-Application/actions)[![PHP Version](https://camo.githubusercontent.com/1015683ef28e870620edc19b6e22b456c0dc170c260fa4645905e93438f607a6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322e312d3737374242342e7376673f6c6f676f3d706870)](https://www.php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

**PSR-7 &amp; PSR-15 нийцсэн хөнгөн, уян хатан HTTP Application цөм****Lightweight, flexible HTTP Application core compliant with PSR-7 &amp; PSR-15**

---

Агуулга / Table of Contents
---------------------------

[](#агуулга--table-of-contents)

1. [Монгол](#1-%D0%BC%D0%BE%D0%BD%D0%B3%D0%BE%D0%BB-%D1%82%D0%B0%D0%B9%D0%BB%D0%B1%D0%B0%D1%80) | 2. [English](#2-english-description) | 3. [Getting Started](#3-getting-started)

---

1. Монгол тайлбар
-----------------

[](#1-монгол-тайлбар)

`codesaur/http-application` нь PSR-7 (HTTP Message) ба PSR-15 (HTTP Server RequestHandler/Middleware) стандартууд дээр суурилсан **минималист**, **өндөр уян хатан**, **middleware суурьтай** Application цөм юм.

Та хүсвэл:

- Router ашиглах (нэг эсвэл олон)
- Middleware удирдах
- Controller/action ашиглах
- Closure route ашиглах
- Exception handler бүртгэх
- Custom request attributes ашиглах

гэх мэтээр өөрийн хүссэн бүтэцтэй web application-ийг хэдхэн мөр кодоор босгох боломжтой.

### Гол боломжууд

[](#гол-боломжууд)

- PSR-7 стандартын ServerRequest + Response
- PSR-15 Middleware &amp; RequestHandler гинжин бүтэц
- Олон Router-ийг нэг Application-д нэгтгэх (multi-router delegation)
- Application-ийг URL prefix-д mount хийх (Router-ууд reusable)
- Controller суурь класс (сонголтот - controller/action хэв маягт ашиглаж болно)
- Per-route middleware (MiddlewareInterface, Closure, class-string)
- Exception Handler (development mode-той)
- Хэт хөнгөн, хурдан - magic API байхгүй, цэвэр separation of concerns

### Дэлгэрэнгүй мэдээлэл

[](#дэлгэрэнгүй-мэдээлэл)

- [Бүрэн танилцуулга](docs/mn/README.md) - Суурилуулалт, хэрэглээ, жишээнүүд
- [API тайлбар](docs/mn/api.md) - Бүх метод, exception-үүдийн тайлбар
- [Шалгалтын тайлан](docs/mn/review.md) - Код шалгалтын тайлан

---

2. English Description
----------------------

[](#2-english-description)

`codesaur/http-application` is a **minimalist**, **highly flexible**, **middleware-based** Application core built on PSR-7 (HTTP Message) and PSR-15 (HTTP Server RequestHandler/Middleware) standards.

You can:

- Use Router (one or many)
- Manage Middleware
- Use Controller/action
- Use Closure routes
- Register Exception handler
- Use Custom request attributes

and build your desired web application structure with just a few lines of code.

### Key Features

[](#key-features)

- PSR-7 Standard ServerRequest + Response
- PSR-15 Middleware &amp; RequestHandler Chain Structure
- Multi-router delegation (combine multiple Routers in one Application)
- Mount Application at a URL prefix (Routers are reusable)
- Controller base class (optional - for controller/action style code if you want)
- Per-route middleware (MiddlewareInterface, Closure, class-string)
- Exception Handler (with development mode)
- Extremely lightweight and fast - no magic API, clean separation of concerns

### Documentation

[](#documentation)

- [Full Documentation](docs/en/README.md) - Installation, usage, examples
- [API Reference](docs/en/api.md) - Complete API documentation
- [Review](docs/en/review.md) - Complete package review and code quality assessment

---

3. Getting Started
------------------

[](#3-getting-started)

### Requirements

[](#requirements)

- PHP **8.2.1+**
- Composer
- PSR-7 compatible HTTP Message implementation (e.g., `codesaur/http-message`) - supplies the `ServerRequestInterface` passed to `handle()` and the `ResponseInterface` prototype passed to the `Application` constructor

### Installation

[](#installation)

Composer ашиглан суулгана / Install via Composer:

```
composer require codesaur/http-application
```

### Quick Examples

[](#quick-examples)

#### Application - Basic Setup

[](#application---basic-setup)

```
use codesaur\Router\Router;
use codesaur\Http\Application\Application;
use codesaur\Http\Application\ExceptionHandler;
use codesaur\Http\Message\ServerRequest;
use codesaur\Http\Message\NonBodyResponse;

// Router-д route бүртгэх / Register routes on Router
$router = new Router();
$router->GET('/', function ($req) {
    echo 'Hello World!';
});

// Application үүсгэх (fallback хариуны prototype дамжуулна) + middleware + router нэмэх
$app = new Application(new NonBodyResponse());
$app->use(new ExceptionHandler());
$app->use($router);

// Хүсэлт боловсруулах / Handle request
$request = (new ServerRequest())->initFromGlobal();
$response = $app->handle($request);
```

#### Router - Dynamic Routes

[](#router---dynamic-routes)

```
$router = new Router();

// Төрөлтэй параметртэй нэртэй route
$router->GET('/user/{int:id}', [UserController::class, 'show'])->name('user.show');

// Олон method-тэй route
$router->POST_PUT('/api/users', [UserController::class, 'save']);

// Параметртэй Closure route
$router->GET('/sum/{int:a}/{uint:b}', function ($req) {
    $params = $req->getAttribute('params');
    echo $params['a'] + $params['b'];
});

$app = new Application(new NonBodyResponse());
$app->use($router);
```

#### Mount - Application-ийг URL prefix-д суулгах / Mounting Application at a URL Prefix

[](#mount---application-ийг-url-prefix-д-суулгах--mounting-application-at-a-url-prefix)

```
use codesaur\Router\Router;

// Router-ууд prefix-ийг мэдэхгүй - reusable
$adminRouter = new Router();
$adminRouter->GET('/users', [UserAdmin::class, 'list'])->name('users');
$adminRouter->GET('/posts', [PostAdmin::class, 'list'])->name('posts');

// Application-ийг entry point дээр mount хийнэ
$app = new Application(new NonBodyResponse());
$app->use($adminRouter);
$app->mount('/dashboard');  // бүх route /dashboard prefix-тэй болов

// match: /dashboard/users -> Router-д /users-аар тааран ажиллана
// generate('users') -> '/dashboard/users'
// $app->mount('/admin') гэвэл нэг ч route өөрчлөхгүйгээр /admin-руу шилжинэ
```

Mount хийсний дараа `$req->getAttribute('application')->generate('name')` нь Application-руу заана учир Controller-ээс URL үүсгэхэд mount prefix автоматаар нэмэгдэнэ.

#### Multi-Router - Олон Router нэгтгэх / Combining Multiple Routers

[](#multi-router---олон-router-нэгтгэх--combining-multiple-routers)

```
use codesaur\Router\Router;

// Module бүрд өөрийн router-тэй
$apiRouter = new Router();
$apiRouter->GET('/api/users', [UserApi::class, 'list'])->name('api.users');

$adminRouter = new Router();
$adminRouter->GET('/admin/dashboard', [Admin::class, 'index'])->name('admin.dash');

$homeRouter = new Router();
$homeRouter->GET('/', $homeHandler);

// Application-д бүгдийг нэгтгэх
$app = new Application(new NonBodyResponse());
$app->use($apiRouter);
$app->use($adminRouter);
$app->use($homeRouter);

// Match order: use() дарааллаар (first-added-wins) - предиктабл default
// generate()/pattern() бүх router дээр first-found-wins хайна
$url = $app->generate('api.users');     // '/api/users'
```

#### Route override - өмнө бүртгэсэн route-ийг зориудаар дарж бичих

[](#route-override---өмнө-бүртгэсэн-route-ийг-зориудаар-дарж-бичих)

```
// Router бүртгэх
$app->use(new ProfileRouter());         // /profile -> ProfileController

// Developer-ийн theme controller-руу шилжүүлэх override
$themeProfile = new Router();
$themeProfile->GET('/profile', [ThemeProfileController::class, 'show'])->name('profile');

$app->override($themeProfile);          // ил override - энэ ялна

// Override lane нь ердийн router-ээс өмнө шалгагдана. Зүгээр use()-ийн
// дараалалд найдаж далд override хийхгүй - bootstrap дотор ил харагдана.
```

#### Controller - controller/action route

[](#controller---controlleraction-route)

```
use codesaur\Http\Application\Controller;

class UserController extends Controller
{
    public function show(int $id): void
    {
        $query = $this->getQueryParams();
        $page = $query['page'] ?? 1;

        echo "User ID: $id, Page: $page";
    }

    public function create(): void
    {
        $data = $this->getParsedBody();
        $name = $data['name'] ?? 'Unknown';

        echo "Created user: $name";
    }
}
```

#### Middleware - PSR-15 &amp; Closure

[](#middleware---psr-15--closure)

```
// PSR-15 Middleware
class AuthMiddleware implements MiddlewareInterface
{
    public function process($req, $handler): ResponseInterface
    {
        // Баталгаажуулалт шалгах / Check authentication
        if (!$this->isAuthenticated($req)) {
            return new Response(401);
        }

        return $handler->handle($req);
    }
}

$app->use(new AuthMiddleware());

// Closure Middleware
$app->use(function ($req, $handler) {
    $startTime = microtime(true);
    $response = $handler->handle($req);
    $duration = microtime(true) - $startTime;

    error_log("Request took: {$duration}s");
    return $response;
});
```

### Running Tests

[](#running-tests)

Тест ажиллуулах / Run tests:

```
# Бүх тестүүдийг ажиллуулах / Run all tests
composer test

# Зөвхөн unit тест / Unit tests only
composer test:unit

# Зөвхөн integration тест / Integration tests only
composer test:integration

# Coverage-тэй тест ажиллуулах / Run tests with coverage
composer test:coverage
```

---

Architecture
------------

[](#architecture)

```
Application
 +-- Middleware stack (PSR-15 + Closure)
 +-- Override lane (list of RouterInterface)      Application::match() [strips mount prefix]
  -> Override lane, then first Router that matches wins (first-added-wins)
  -> Per-route middleware chain (PSR-15 onion model)
  -> Controller/action OR Closure
  -> Response

```

**URL Generation:** `Application::generate('name')` -&gt; finds name in first Router that has it -&gt; prepends mount prefix -&gt; returns URL.

---

Changelog
---------

[](#changelog)

- [CHANGELOG.md](CHANGELOG.md) - Full version history

Contributing &amp; Security
---------------------------

[](#contributing--security)

- [Contributing Guide](.github/CONTRIBUTING.md)
- [Security Policy](.github/SECURITY.md)

License
-------

[](#license)

This project is licensed under the MIT License.

Author
------

[](#author)

**Narankhuu**

**codesaur ecosystem:**

###  Health Score

53

—

FairBetter than 96% of packages

Maintenance97

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity68

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~24 days

Recently: every ~36 days

Total

78

Last Release

31d ago

Major Versions

v2.5 → v3.02021-09-21

v3.1 → v4.02021-09-29

v4.7 → v5.02021-10-06

v5.9.0 → v6.0.02026-01-08

v6.0.3 → v7.0.02026-06-03

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4127594?v=4)[Наранхүү Н](/maintainers/codesaur)[@codesaur](https://github.com/codesaur)

---

Top Contributors

[![codesaur](https://avatars.githubusercontent.com/u/4127594?v=4)](https://github.com/codesaur "codesaur (121 commits)")

---

Tags

httppsr-7routerpsr-15applicationcodesaurmongolmongolianarankhuucodenкодзаврнаранхүүкоденhttp applicationserver request handler

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/codesaur-http-application/health.svg)

```
[![Health](https://phpackages.com/badges/codesaur-http-application/health.svg)](https://phpackages.com/packages/codesaur-http-application)
```

###  Alternatives

[guzzlehttp/psr7

PSR-7 message implementation that also provides common utility methods

8.0k1.1B4.0k](/packages/guzzlehttp-psr7)[mezzio/mezzio

PSR-15 Middleware Microframework

3923.8M126](/packages/mezzio-mezzio)[sunrise/http-router

A powerful solution as the foundation of your project.

17451.6k10](/packages/sunrise-http-router)[laminas/laminas-stratigility

PSR-7 middleware foundation for building and dispatching middleware pipelines

587.2M101](/packages/laminas-laminas-stratigility)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28591.3k3](/packages/mezzio-mezzio-authentication-oauth2)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

131.7M39](/packages/mezzio-mezzio-authentication)

PHPackages © 2026

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