Builder for stack middlewares based on HttpKernelInterface.

Related tags

Middlewares builder
Overview

Stack/Builder

Builder for stack middlewares based on HttpKernelInterface.

Stack/Builder is a small library that helps you construct a nested HttpKernelInterface decorator tree. It models it as a stack of middlewares.

Example

If you want to decorate a silex app with session and cache middlewares, you'll have to do something like this:

use Symfony\Component\HttpKernel\HttpCache\Store;

$app = new Silex\Application();

$app->get('/', function () {
    return 'Hello World!';
});

$app = new Stack\Session(
    new Symfony\Component\HttpKernel\HttpCache\HttpCache(
        $app,
        new Store(__DIR__.'/cache')
    )
);

This can get quite annoying indeed. Stack/Builder simplifies that:

$stack = (new Stack\Builder())
    ->push('Stack\Session')
    ->push('Symfony\Component\HttpKernel\HttpCache\HttpCache', new Store(__DIR__.'/cache'));

$app = $stack->resolve($app);

As you can see, by arranging the layers as a stack, they become a lot easier to work with.

In the front controller, you need to serve the request:

use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();
$response = $app->handle($request)->send();
$app->terminate($request, $response);

Stack/Builder also supports pushing a callable on to the stack, for situations where instantiating middlewares might be more complicated. The callable should accept a HttpKernelInterface as the first argument and should also return a HttpKernelInterface. The example above could be rewritten as:

$stack = (new Stack\Builder())
    ->push('Stack\Session')
    ->push(function ($app) {
        $cache = new HttpCache($app, new Store(__DIR__.'/cache'));
        return $cache;
    })
;

Inspiration

Comments
  • Add run() function

    Add run() function

    I think that run() function could be helpful (in the same way than it's in Silex). It's just a shortcut, especially when we are going to use the Request from globals (but maybe there's a good reason to not to include it in StackedHttpKernel)

    opened by gonzalo123 8
  • Allow pushing callables on to the builder

    Allow pushing callables on to the builder

    No type checking on the return of the factory, but I think it will be alright.

    The use case that drove this was based on discussion in #silex-php, if I was mapping authentication schemes to certain paths, I'd want to do it like this:

    
    $builder->push(function ($app) {
        return = new UrlMap($app, [
            '/api' => new Hawk($app, []),
            '/admin' => new BasicAuth($app, []),
        ]);
    })
    
    

    I guess that could start to generate a complicated stack, but it's the way I'd roll. I think you can add express.js middlewares with an url prefix, should really check there implementation.

    I can't think of any other use cases at the moment, but this would make the builder very flexible going forward and it will be a lot easier for little builder helpers as well, e.g. we could quickly decorate a builder with a pushPrefixed method.

    opened by davedevelopment 5
  • Assume Terminable middlewares will delegate (fixes #10)

    Assume Terminable middlewares will delegate (fixes #10)

    This is a much simpler and cheaper solution than #11.

    We are defining terminables to never be conditional. They must always delegate. This makes it safe to always call them.

    Now we must prevent terminables from being called more than once. If we assume that a terminable will delegate to the next terminable middleware in the chain, we can skip terminate calls while the previous middleware was terminable.

    We only need to kick off the chain for two cases:

    • If the first element in the chain is terminable
    • Any terminable followed by a non-terminable
    opened by igorw 4
  • Build safe chain of terminable kernels (fixes #10)

    Build safe chain of terminable kernels (fixes #10)

    • Should not call terminate() more than once (it was potentially factorial of stack size)
    • Allow middlewares to delegate terminate() calls
    • Increases stack size by number of non-terminable middlewares wrapping a terminable

    If possible, we should find a way to reduce stack size, as it is expensive for GC.

    Note: This implementation implicitly defines the semantics of Terminable to be as follows. A middleware that implements Terminable must always delegate to the next layer. If Terminable is not implemented, it will be wrapped in a StackedHttpKernel that handles the terminate() delegation. The delegation must not be conditional.

    A consequence of this is that all middlewares will be called every time, each one exactly once.

    opened by igorw 3
  • Remove Silex as a dependency

    Remove Silex as a dependency

    Now that Silex is in maintenance mode and Symfony 4 is recommended instead—I would suggest that Silex is removed as a dependency in dev.

    This PR also updates the psr/log and symfony/polyfill-mbstring libraries.

    opened by mikealmond 2
  • Why PHP 5.4?

    Why PHP 5.4?

    Does this library need to require PHP 5.4 in the its composer.json? I did a quick scan of the code and nothing is jumping out at me that won't work on 5.3.

    opened by taylorotwell 2
  • Support Symfony 6.

    Support Symfony 6.

    Drupal uses stack/builder and we're working on Symfony 6 compatibility for our upcoming Drupal 10 release. A new release with these constraints would be great if that's doable.

    opened by catch56 1
  • [1.0.6] Add KernelStack

    [1.0.6] Add KernelStack

    The kernelStack simplifise using stack middlewares.

    example :

    $app = new Silex\Application();
    
    $app->get('/', function () {
        return 'Hello World!';
    });
    
    $app = new Stack\KernelStack($app);
    
    $app->push('Stack\Session');
    
    $request = Request::create('/');
    
    $response = $app->handle($request);
    
    $response->send();
    
    $app->terminate($request,$response);
    
    opened by azjezz 1
  • tweaked code

    tweaked code

    $args = $spec; variable $spec not used in code

    $kernelClass = $firstArg;

    $kernelClass only used as replacement $firstArg for new instance of reflection class

    opened by LionsHead 0
  • Document delegation of terminate()

    Document delegation of terminate()

    As a follow-up to #10, since we have established that terminate() should always delegate, we should document this properly.

    • The README of stack/builder should explain what the expected behaviour of terminable middlewares is, and what happens if one of the middlewares in the chain is not terminable.
    • There should be some information on the stack website (maybe a STACK-n convention) explaining that middlewares implementing Terminable MUST delegate terminate(), always and unconditionally.
    opened by igorw 0
  • Symfony 6 and PHPUnit 9.

    Symfony 6 and PHPUnit 9.

    Drupal uses stack/builder and so we need to add Symfony 6 compatibility here for us to be able to upgrade.

    Locally the tests pass for me with these changes:

    $ vendor/bin/phpunit
    PHPUnit 9.5.11 by Sebastian Bergmann and contributors.
    
    Warning:       Your XML configuration validates against a deprecated schema.
    Suggestion:    Migrate your XML configuration using "--migrate-configuration"!
    
    ...............                                                   15 / 15 (100%)
    
    Time: 00:00.021, Memory: 8.00 MB
    
    OK (15 tests, 22 assertions)
    

    However the new return type in StackedHttpKernel::handle() might mean this has to be a 2.0 release?

    opened by longwave 1
Owner
null
[DEPRECATED] Collection of PSR-7 middlewares

This package is deprecated in favor of the new PSR-15 standard. Check it out here psr7-middlewares Collection of PSR-7 middlewares. Requirements PHP >

Oscar Otero 669 Dec 27, 2022
Common utils used by PSR-15 middlewares

middlewares/utils Common utilities used by the middlewares' packages: Factory Dispatcher CallableHandler HttpErrorException Installation This package

Middlewares 47 Jan 2, 2023
Sistema de Rotas com Controllers e Middlewares

Sistema de Rotas com Controllers e Middlewares

adev 0 May 30, 2022
🦭 Kirby, but headless only – KQL with bearer token, Express-esque middlewares & more

Kirby Headless Starter ℹ️ Send a Bearer test authorization header with a request to the live playground to test this headless starter. This starter ki

Johann Schopplich 36 Dec 28, 2022
A set of shady Slim Framework middlewares that can solve some annoyances...

Shady A set of shady Slim Framework middlewares that can solve some annoyances... What does it contain? Available middlewares: ApacheVirtualHostFix Ur

Jan-Age Laroo 7 Jun 22, 2021
A modern Docker LAMP stack and MEAN stack for local development

The Devilbox Usage | Architecture | Community | Features | Intranet | Screenshots | Contributing | Logos | License Support for valid https out of the

cytopia 4k Jan 8, 2023
Facebook Query Builder: A query builder for nested requests in the Facebook Graph API

A query builder that makes it easy to create complex & efficient nested requests to Facebook's Graph API to get lots of specific data back with one request.

Sammy Kaye Powers 92 Dec 18, 2022
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 5, 2023
Livewire Package to display Toast Notification based on TALL Stack.

livewire-toast Livewire Package to display Toast Notification based on TALL Stack. Requirements Make sure that Livewire is installed properly on your

AscSoftwares 35 Nov 12, 2022
Shopware 6 is an open source ecommerce platform based on a quite modern technology stack that is powered by Symfony and Vue.js.

Shopware 6 Realize your ideas - fast and without friction. Shopware 6 is an open source ecommerce platform based on a quite modern technology stack th

Shopware 2.1k Dec 31, 2022
Real world Conduit App based on Laravel Livewire stack

Laravel Livewire codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld spec and API. Demo Github

Ricardo Sawir 18 Nov 14, 2022
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 7, 2023
Laravel API architecture builder based on artisan commands.

??‍?? API-Formula Laravel API architecture builder based on artisan commands. This package provides a nice and fluent way to generate combined control

Krševan Lisica 1 Jan 16, 2022
An advanced yet user-friendly content management system, based on the full stack Symfony framework combined with a whole host of community bundles

An advanced yet user-friendly content management system, based on the full stack Symfony framework combined with a whole host of community bundles. It provides a full featured, multi-language CMS system with an innovative page and form assembling process, versioning, workflow, translation and media managers and much more.

Kunstmaan | Accenture Interactive 374 Dec 23, 2022
A DynamoDB based Eloquent model and Query builder for Laravel.

Laravel DynamoDB A DynamoDB based Eloquent model and Query builder for Laravel. You can find an example implementation in kitar/simplechat. Motivation

Satoshi Kita 146 Jan 2, 2023
application/hal builder / formatter for PHP 5.4+

Nocarrier\Hal This is a library for creating documents in the application/hal+json and application/hal+xml hypermedia formats It requires PHP 5.4 or l

Ben Longden 204 Sep 28, 2022
A lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.

Idiorm http://j4mie.github.com/idiormandparis/ Feature/API complete Idiorm is now considered to be feature complete as of version 1.5.0. Whilst it wil

Jamie Matthews 2k Dec 27, 2022
Drag and Drop Website Builder and CMS with E-commerce

Microweber: Drag-and-Drop CMS Current version: 1.2 running on Laravel 8! Download | What is Microweber? | Core features of Microweber | Requirements |

Microweber 2.6k Dec 28, 2022
High performance, full-stack PHP framework delivered as a C extension.

Phalcon Framework Phalcon is an open source web framework delivered as a C extension for the PHP language providing high performance and lower resourc

The Phalcon PHP Framework 10.7k Jan 8, 2023
CleverStyle Framework is simple, scalable, fast and secure full-stack PHP framework

CleverStyle Framework is simple, scalable, fast and secure full-stack PHP framework. It is free, Open Source and is distributed under Free Public Lice

Nazar Mokrynskyi 150 Apr 12, 2022