hermes-php / asset-middleware
A middleware to load public assets
Requires
- php: >=7.2
- psr/container: ^1.0
- psr/http-factory: ^1.0
- psr/http-server-middleware: ^1.0
- ralouphie/mimey: ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.13
- phpunit/phpunit: ^7.5
- zendframework/zend-diactoros: ^2.1
This package is auto-updated.
Last update: 2019-08-18 18:26:50 UTC
README
Provides static files and asset loading when running in a un-traditional web server like Road Runner or React PHP.
Installation
composer require hermes-php/asset-middleware
Usage
The purpose of the asset middleware is to build a response containing a file if a certain uri matches an existing file in a directory.
The only requirement is that you provide an implementation of FileSource
.
The AssetMiddleware
comes with a factory that will allow you to instantiate in
an easier fashion. By default, it will inject a service named Hermes\Asset\FileSource\FileSource
into it.
Building the File Source
There are three default implementations of FileSource
. Two of them are decorators.
The ResponseFactoryFileSource
has a ResponseFactoryInterface
as a dependency.
It's shouldServeFile
method returns true if the request method is GET and
the serveFile
method returns an instance of ResponseInterface
using the factory.
The decorators are meant to be composed on top of the ResponseFactoryFileSource
,
even though you can pass them any FileSource
implementation.
The AttachBodyFileSourceDecorator
checks in the provided path matching the
Request Uri exists (and also that the decorated FileSource returns true).
If it does, then creates an stream out of that file using a PSR7 Stream Factory
implementation, and injects it in the response as the body.
The ContentTypeFileSourceDecorator
checks if the provided path has an extension
that is in a map of extensions and content types allowed to be served. These include,
by default, the most common file extensions that your application will be serving,
but they are totally configurable.
An example of an implementation of a FileSource could look like this:
<?php
use Hermes\Asset\FileSource\ContentTypeFileSourceDecorator;
use Hermes\Asset\FileSource\AttachBodyFileSourceDecorator;
use Hermes\Asset\FileSource\ResponseFactoryFileSource;
$fileSource = new ContentTypeFileSourceDecorator(
new AttachBodyFileSourceDecorator(
new ResponseFactoryFileSource(new \Zend\Diactoros\ResponseFactory()),
new \Zend\Diactoros\StreamFactory(),
'/path/to/assets'
),
// You can provide an extension content type map that serves only these files.
[
'ext' => 'some/content-type',
'other' => 'other/content-type'
]
);
You can implement custom decorators on top of these to attach transfer encoding header and and other things. We opted for composition to design the file source so you can reuse different parts and keep everything as flexible as possible. It scales much better than inheritance.
Of course, you can dump all this and make your own FileSource
implementation
from scratch.