PHPackages                             linkeddatacenter/usilex - 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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. linkeddatacenter/usilex

AbandonedArchivedLibrary[PSR &amp; Standards](/categories/psr-standards)

linkeddatacenter/usilex
=======================

Super lightweight framework based on a subset of SILEX. Great for micro services and JAMstack

1.2.0(7y ago)359[1 PRs](https://github.com/linkeddatacenter/uSilex/pulls)MITPHPPHP ^7.1.3

Since Oct 1Pushed 3y ago2 watchersCompare

[ Source](https://github.com/linkeddatacenter/uSilex)[ Packagist](https://packagist.org/packages/linkeddatacenter/usilex)[ RSS](/packages/linkeddatacenter-usilex/feed)WikiDiscussions master Synced yesterday

READMEChangelog (4)Dependencies (18)Versions (6)Used By (0)

[![µSilex logo](logo.png)](logo.png)

µSilex
======

[](#µsilex)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b85f028d7a4ab05e800d7b26428b8d79b48d1ee6d9d13008ec9435216680e5af/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c696e6b65646461746163656e7465722f7553696c65782e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/linkeddatacenter/usilex)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/ae389f6e8f3b842aae030ad1a38732ae6985f272126ac7ee0d656360b56228ed/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6c696e6b65646461746163656e7465722f7553696c65782f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/linkeddatacenter/uSilex/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/8a5ac8472acec449094604b625dffc7006c1e8cd5d8dc78274ca69eef3cf6f1f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6c696e6b65646461746163656e7465722f7553696c65782f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/linkeddatacenter/uSilex/?branch=master)[![Build Status](https://camo.githubusercontent.com/a41c56c94f0e7609db4c03ea3f1477a55c415235e98f23653a45606687a9e14d/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6c696e6b65646461746163656e7465722f7553696c65782f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/linkeddatacenter/uSilex/build-status/master)

µSilex (aka micro silex) is a micro framework inspired by Pimple and PSR standards. All with less than 100 lines of code!

This project is a try to build a standard middleware framework for developing micro-services and APIs endpoints that require maximum performances with a minimum of memory footprint.

Why [Pimple](https://pimple.symfony.com/)? Because it is lazy, consistent, fast, elegant and small (about 80 lines of code). What else?

Why [PSR standards](https://www.php-fig.org/psr)? Because it is a successful community project with a lot of good implementations (psr15-middlewares, Zend stratigility, Guzzle, etc. etc.).

Why µSilex? Silex was a great framework now abandoned in favor of Symfony + Flex. This is good when you need more power and flexibility. But you have to pay a price in terms of complexity and memory footprint. µSilex it is a new project that covers a small subset of the original Silex project: a µSilex Application is just a Pimple Container implementing the [PSR-15 specifications](https://www.php-fig.org/psr/psr-15/). That's it.

As a matter of fact, in the JAMStack, Docker and XaaS era, you can let a lot of conventional framework features to other components in the system application architecture (i.e. caching, authentication, security, monitoring, rendering, etc. etc).

Is µSilex a replacement of Silex? No, but it could be used to build your own "Silex like"framework.

There are alternatives to µSilex? Yes of course. For example, the [Zend Expressive](https://docs.zendframework.com/zend-expressive/) component of the Zend Framework shares similar principles. But it is not "container focused" and it is bound to Zend libraries. Besides routing, Zend Expressive implements "piping" as a mechanism for adding middlewares to your application.

µSilex is based on a few principles:

- keep it **simple**: so you can understand all your code;
- keep it **small**: so you can control your project;
- keep it **fast**: well, keep it faster...;
- use **PSR standards**: do not reinvent the wheel;
- adopt the **middlewares** architecture;
- **"one-for-all" does not exist!**. And µSilex is not an exception. Select the right framework for your problem.

Have a nice day!

Install
-------

[](#install)

`compose require linkeddatacenter/usilex`

Overview
--------

[](#overview)

Basically a µSilex provides the class **Application** that is a Pimple container that implements both the PSR-15 middleware interface and PSR-11 Container interface.

Middleware is now a very popular topic in the developer community, The idea behind it is “wrapping” your application logic with additional request processing logic, and then chaining as much of those wrappers as you like. So when your server receives a request, it would be first processed by your middlewares, and then after you generate a response it will also be processed by the same set (image from Zend Expressive).

[![architecture](architecture.png)](architecture.png)

Note that in this model, the traditional *routing by controller* is just an optional step in the middleware pipeline.

A middleware is a piece of software that implements the PSR-15 middleware interface:

```
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;

class MyMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
        ): ResponseInterface
    {
        //here your code that returns a response or passes the control to the handler
    }
}
```

µSilex is not bound to any specific implementations (apart from Pimple) nor to any middleware implementation.

Instead, µSilex realizes a framework to use existing standard implementations. µSilex adopts PSR-7 specifications for HTTP messages, PSR-15 for managing HTTP handles and middleware and PSR-11 for containers.

Usage
-----

[](#usage)

To bind µSilex with specific interface specifications, you need to configure some entries in the container:

- **uSilex.request**: a service that instantiates an implementation of PSR-7 server request object
- **uSilex.responseEmitter**: an optional callable that echoes the HTTP. If not provided, no output is generated.
- **uSilex.exceptionHandler** a callable that generates an HTTP response from a PHP Exception. If not provided just an HTTP 500 header with a text body is output
- **uSilex.httpHandler**: a service that instantiates an implementation of the PSR-15 HTTP handler

µSilex Application exposes the *run* method that realizes typical server process workflow:

- creates a request using uSilex.request service
- calls the uSilex.httpHandler
- emits the HTTP response calling uSilex.responseEmitter

If some PHP exceptions are thrown in the process, they are translated in Response by uSilex.exceptionHandler and then emitted by uSilex.responseEmitter.

The signature for uSilex.responseEmitter is `function ($response) { echo ....}` . The signature for uSilex.exceptionHandler is `function ($exception, $request) {}`.

There are tons of libraries that implement great reusable middlewares and HTTP handlers that are fully compatible with µSilex. For example see [MW library](https://github.com/middlewares/psr15-middlewares)). µSilex is also compatible with a lot of Silex Service Providers and with some Silex Application traits.

You can create your custom framework just selecting the components that fit your needs. This fragment uses the [Relay](http://relayphp.com/2.x) library for PSR-15 http handler and [Diactoros](https://docs.zendframework.com/zend-diactoros/) for PSR-7 http messages.

```
require_once __DIR__.'/../vendor/autoload.php';
include "MyMiddleware.php"; // here your MyMiddleware class definition
$app = new \uSilex\Application;
$app['uSilex.request'] = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
$app['uSilex.responseEmitter'] = $app->protect(function($response) {echo $response->getBody(); });
$app['uSilex.httpHandler'] = function($app) {
    return new \Relay\Relay([new MyMiddleware($app)]);
};
$app->run();
```

### the µSilex service providers

[](#the-µsilex-service-providers)

out-of-the-box µSilex give to you a set of Service Providers that you can use as a model to implement yours.

#### Provider\\Psr7\\DiactorosServiceProvider

[](#providerpsr7diactorosserviceprovider)

Bound a µSilex application to the [Zend Diactoros](https://docs.zendframework.com/zend-diactoros/) implementation for Psr7 specifications.

#### Provider\\Psr7\\GuzzleServiceProvider

[](#providerpsr7guzzleserviceprovider)

Bound a µSilex application to the [Guzzle](http://docs.guzzlephp.org/en/stable/psr7.html) implementation for Psr7 specifications.

#### Provider\\Psr15\\RelayServiceProvider

[](#providerpsr15relayserviceprovider)

Bound a µSilex application to [Relay](https://github.com/relayphp/Relay.Relay), a fast, no frill implementation of the PSR-15 specifications.

#### Provider\\Psr15\\ZendPipeServiceProvider

[](#providerpsr15zendpipeserviceprovider)

Bound a µSilex application to *MiddlewarePipe* part of the [zend-stratigility library](https://github.com/zendframework/zend-stratigility/) Psr15 implementation.

### Configuring new service providers

[](#configuring-new-service-providers)

µSilex Service provider are normal Pimple service providers that, optionally, define the method *boot*. This method will be called only once by the application method *boot*. Use this feature only if strictly necessary. The boot method is called automatically by the Application run method.

A best practice to write a PSR-15 service provider is to allow users to declare middlewares as Pimple services and to allow users to define the middleware queue (i.e. pipeline) in an array with the name *handler.queue*. The *handler.queue* element can also be a service that resolves in an implementation of the iterable interface. For instance:

```
...
$app= new Application;
$app->register( new MyPsr7ServiceProvider() };
$app['my.router'] = function($app) { return new \My\RouterMiddleWare($app) };
$app['my.notfound'] = function($app) { return new \My\NotFoundMiddleWare($app) };
$app['handler.queue'] = [
    'my.router'
    'my.notfound'
];
$app['uSilex.httpHandler'] = function($app) {
   return new MyHttpHandler($app['handler.queue']);
};
$app->boot()->run();
```

### Other tools

[](#other-tools)

µSilex also provides two ready to use anti-pattern traits: \\uSilex\\Psr11Trait that implements a PSR-11 interface and \\uSilex\\ContainerAwareTrait that attach a PSR-11 container (e.g a µSilex Application) to any object.

A complete example
------------------

[](#a-complete-example)

```
