by Enrico Zimuel
Senior Software Engineer
Rogue Wave Software (USA)
APIConf 2018, Turin (Italy), 21th Jun
|
Sviluppare in PHP 7 *pp. 352, Tecniche Nuove, 2017 * in Italian |
Global variables (bad!):
// Request
$header = $request->getHeader('Accept');
$query = $request->getQueryParams();
$body = $request->getBodyParams();
// Response
$response = $response->withStatus(418, "I'm a teapot");
$response = $response->withBodyParams(json_encode($body));
A function that gets a request and generates a response
function ($request)
{
// do something with $request
return $response;
}
Create a pipeline of execution
function ($request, $delegate)
{
// delegating another middleware
$response = $delegate($request);
return $response;
}
function ($request, $delegate) use ($cache)
{
if ($cache->has($request)) {
return $cache->get($request);
}
$response = $delegate($request);
$cache->set($request, $response);
return $response;
}
The PHP framework for middleware applications
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Application;
$container = require 'config/container.php';
$app = $container->get(Application::class);
$app->pipe('/api/ping', function($request) {
return new JsonResponse(['ack' => time()]);
});
// or $app->pipe('/api/ping', \App\Handler\PingHandler::class);
$app->run();
use Psr\Http\Message\ResponseInterface; // PSR-7
use Psr\Http\Message\ServerRequestInterface; // PSR-7
use Psr\Http\Server\RequestHandlerInterface; // PSR-15
use Zend\Diactoros\Response\JsonResponse;
class PingHandler implements RequestHandlerInterface
{
public function handle(
ServerRequestInterface $request
) : ResponseInterface
{
return new JsonResponse(['ack' => time()]);
}
}
$app->route('/api/users[/{id}]', [
Authentication\AuthenticationMiddleware::class,
Authorization\AuthorizationMiddleware::class,
Api\Action\UserAction::class
], ['GET', 'POST', 'PATCH', 'DELETE'], 'api.users');
// or route each HTTP method
$app->get('/api/users[/{id}]', ..., 'api.users.get');
$app->post('/api/users', ..., 'api.users.post');
$app->patch('/api/users/{id}', ..., 'api.users.patch');
$app->delete('/api/users/{id}', ..., 'api.users.delete');
You can start using Expressive with composer:
composer create-project zendframework/zend-expressive-skeleton <dir>
pecl install swoole
$http = new swoole_http_server("127.0.0.1", 9501);
$http->on("start", function ($server) {
echo "Started at http://127.0.0.1:9501\n";
});
$http->on("request", function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World\n");
});
$http->start();
Use zendframework/zend-expressive-swoole library
(dev version):
composer require zendframework/zend-expressive-swoole:dev-master
Usage:
php public/index.php
Runs at localhost:8080 by default
Contact: enrico.zimuel [at] roguewave.com
This work is licensed under a
Creative Commons Attribution-ShareAlike 3.0 Unported License.
I used reveal.js to make this presentation.