Giter Site home page Giter Site logo

middleland's Introduction

Middleland

Latest Version on Packagist Software License Testing Quality Score

Simple (but powerful) PSR-15 middleware dispatcher:

Requirements

Example

use Middleland\Dispatcher;

$middleware = [
    new Middleware1(),
    new Middleware2(),
    new Middleware3(),

    // A dispatcher can be used to group middlewares
    new Dispatcher([
        new Middleware4(),
        new Middleware5(),
    ]),

    // You can use closures
    function ($request, $next) {
        $response = $next->handle($request);
        return $response->withHeader('X-Foo', 'Bar');
    },

    // Or use a string to create the middleware on demand using a PSR-11 container
    'middleware6'

    // USE AN ARRAY TO ADD CONDITIONS:

    // This middleware is processed only in paths starting by "/admin"
    ['/admin', new MiddlewareAdmin()],

    // This is processed in DEV
    [ENV === 'DEV', new MiddlewareAdmin()],

    // Use callables to create other conditions
    [
        function ($request) {
            return $request->getUri()->getScheme() === 'https';
        },
        new MiddlewareHttps()
    ],

    // There are some matchers included in this library to create conditions
    [
        new Pattern('*.png'),
        new MiddlewareForPngFiles()
    ],

    //And use several for each middleware
    [
        ENV === 'DEV',
        new Pattern('*.png'),
        new MiddlewareForPngFilesInDev()
    ],
];

$dispatcher = new Dispatcher($middleware, new Container());

$response = $dispatcher->dispatch(new Request());

Matchers

As you can see in the example above, you can use an array of "matchers" to filter the requests that receive middlewares. You can use callables, instances of Middleland\Matchers\MatcherInterface or booleans, but for comodity, the string values are also used to create Middleland\Matchers\Path instances. The available matchers are:

Name Description Example
Path Filter requests by base path. Use exclamation mark for negative matches new Path('/admin'), new Path('!/not-admin')
Pattern Filter requests by path pattern. Use exclamation mark for negative matches new Pattern('*.png') new Pattern('!*.jpg')
Accept Filter requests by Accept header. Use exclamation mark for negative matches new Accept('text/html') new Accept('!image/png')

How to create matchers

Just use a callable or an instance of the Middleland\Matchers\MatcherInterface. Example:

use Middleland\Matchers\MatcherInterface;
use Psr\Http\Message\ServerRequestInterface;

class IsAjax implements MatcherInterface
{
    public function __invoke(ServerRequestInterface $request): bool
    {
    	return $request->getHeaderLine('X-Requested-With') === 'xmlhttprequest';
	}
}

Please see CHANGELOG for more information about recent changes.

The MIT License (MIT). Please see LICENSE for more information.

middleland's People

Contributors

filisko avatar fisharebest avatar jan-di avatar kfreiman avatar oscarotero avatar raisoblast avatar tbreuss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

middleland's Issues

add middleware on the fly

is there a possibility to add a middleware while dispatching the queue?
a common scenario like laravel did, is:
bind middleware to a specific route and dispatch this middleware if the route gets used.

the problem is, that the router process is a middleware too. i only get the route specific middleware after resolving the route. and therefore i am on the dispatched queue.

PHP8 Support

Hello,

I am currently checking which of the libraries I use support php8. Therefore I also checked this and tried what happens when I update the dependencies and run with php8.

The dispatcher and its production dependencies itself seems to run without changes needed. With a very small change, all tests are successful (I will create a PR for this), but only if phpunit and laminas is upgraded. php-cs-fixer is currently not supported (see PHP-CS-Fixer/PHP-CS-Fixer#4702)

That means, to make sure dev dependencies are compatible, they would have to be updated. But for example phpunit 9 only supports 7.3+, which would also raise the minimum version in this library. Is this something for a "version 2" to support php8+? Or upgrade the dev dependencies to test under php8 and keep the minimum version 7.0 anyways?

What do you think about this?

Show an example of using your library

My version:

<?php

// PHP-DI
$container = new DI\Container();

// https://docs.laminas.dev/laminas-diactoros/v2/usage/
$request = Laminas\Diactoros\ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);

$middleware = [
    function ($request, $next) {
        $response = $next->handle($request);
        return $response->withHeader('X-Foo1', 'Bar1');
    },

    function ($request, $next) {
        $response = $next->handle($request);
        return $response->withHeader('X-Foo2', 'Bar2');
    },
];

$dispatcher = new Middleland\Dispatcher($middleware, $container);

try {
    $response = $dispatcher->dispatch($request); // !!! ERROR -> Uncaught LogicException: Middleware queue exhausted 
} catch (Exception $e) {
    echo 'error'; 
}

print_r($response); // ERROR! Warning: Undefined variable $response 

Why is there an error? Please show an example of usage!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.