The goal of this RFC is to simplify the usage of Expressive.
I would like to write a simple Expressive application similar to the approach of Slim (see the code reported here). The idea is to offer a very quick way for newbies to use Expressive, without all the classes, folders and configuration provided by zend-expressive-skeleton. For example, I would like to write a code something like this:
require 'vendor/autoload.php';
use Zend\Expressive\Application;
$app = new Application(/* ... */);
$app->get('/', function($req, $delegate){
echo "Hello World!";
});
$app->run();
I figured out a simple way to accomplish this without any BC break of the existing zend-expressive-skeleton
. The idea is to move the $app
instance of public/index.php
in a separate file and remove the usage of anonymous functions in config/pipeline.php
and config/routes.php
. Basically, my proposal is to go back to v.2 of skeleton implementation for these 2 files. This will also facilitate the migration of existing applications from v.2 to v.3.
This is the code change that I’m proposing:
config/app.php
$container = require 'container.php';
$app = $container->get(\Zend\Expressive\Application::class);
require 'pipeline.php';
return $app;
config/pipeline.php
$app->pipe(Zend\Stratigility\Middleware\ErrorHandler::class);
$app->pipe(Zend\Expressive\Helper\ServerUrlMiddleware::class);
$app->pipe(Zend\Expressive\Router\Middleware\RouteMiddleware::class);
$app->pipe(Zend\Expressive\Router\Middleware\ImplicitHeadMiddleware::class);
$app->pipe(Zend\Expressive\Router\Middleware\ImplicitOptionsMiddleware::class);
$app->pipe(Zend\Expressive\Router\Middleware\MethodNotAllowedMiddleware::class);
$app->pipe(Zend\Expressive\Helper\UrlHelperMiddleware::class);
$app->pipe(Zend\Expressive\Router\Middleware\DispatchMiddleware::class);
$app->pipe(Zend\Expressive\Handler\NotFoundHandle::class);
config/routes.php
$app->get('/', App\Handler\HomePageHandler::class, 'home');
$app->get('/api/ping', App\Handler\PingHandler::class, 'api.ping');
With these new configuration files, the public/index.php
becomes:
if (PHP_SAPI === 'cli-server' && $_SERVER['SCRIPT_FILENAME'] !== __FILE__) {
return false;
}
chdir(dirname(__DIR__));
require 'vendor/autoload.php';
(function () {
$app = require 'config/app.php';
require 'config/routes.php';
$app->run();
})();
Using this simple configuration approach, we can write a simple application as follows:
require 'vendor/autoload.php';
$app = require 'config/app.php';
$app->get('/', function($request, $handler) {
echo "Hello World!";
});
$app->run();
Note that in the config/app.php
I’m not including the routing specification (that remains in the public/index.php
file). The $app
instance benefits from all the configuration services of the zend-expressive-skeleton
application, including a routing adapter, a template system, an error handler, etc.
The proposed code change for the skeleton application is published here.