Skip to content

Instantly share code, notes, and snippets.

@codeliner
Created October 25, 2016 09:20
Show Gist options
  • Save codeliner/42b92174652af6c984170a8a1f9adb14 to your computer and use it in GitHub Desktop.
Save codeliner/42b92174652af6c984170a8a1f9adb14 to your computer and use it in GitHub Desktop.
Zend Strategility + FastRoute - lean microservice approach
<?php
declare(strict_types = 1);
use \Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
chdir(dirname(__DIR__));
require 'vendor/autoload.php';
$app = new \Zend\Stratigility\MiddlewarePipe();
$app->pipe('/api/v1', function (Request $req, Response $res, callable $next) {
/** @var FastRoute\Dispatcher $router */
$router = require 'app/config/router.php';
/** @var \Interop\Container\ContainerInterface $container */
$container = require 'app/config/container.php';
$route = $router->dispatch($req->getMethod(), $req->getUri()->getPath());
if ($route[0] === FastRoute\Dispatcher::NOT_FOUND) {
return $res->withStatus(404);
}
if ($route[0] === FastRoute\Dispatcher::METHOD_NOT_ALLOWED) {
return $res->withStatus(405);
}
foreach ($route[2] as $name => $value) {
$req = $req->withAttribute($name, $value);
}
$httpHandler = $container->get($route[1]);
return $httpHandler($req, $res);
});
$app->pipe('/', function ($req, $res, $next) {
return new \Zend\Diactoros\Response\TextResponse('It works');
});
//Register simple error handler (don't use it in production!!!)
$app->pipe(function($err, $req, $res, $next) {
if ($err instanceof \Throwable) {
return new \Zend\Diactoros\Response\TextResponse((string)$err, 500);
}
});
$server = \Zend\Diactoros\Server::createServer(
$app,
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$server->listen();
<?php
declare(strict_types = 1);
return \FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $r) {
$r->addRoute(
'PUT',
'/companies/{company:\d+}/customers/{client_id:\d+}',
\Acme\CustomersWrite\Http\ImportBasicCustomerDataAction::class
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment