dev-master
9999999-devProduction-grade REST-API App-class for PHP SLIM
MIT
The Requires
- slim/slim ^3.0
- patricksavalle/slim-request-params dev-master
- phpunit/phpunit 5.3.*
- palanik/corsslim dev-slim3
- pavlakis/slim-cli ^1.0
Wallogit.com
2017 © Pedro Peláez
Production-grade REST-API App-class for PHP SLIM
Uses PHP 7.x syntax, (*1)
Turns the default SLIM App-class into a production-grade JSON REST-API base-class: - adds (GET, POST and header) parameter validation for added security and self-documentation - adds robust exception and assert handling / sets-up the PHP interpreter for exceptions so 'normal' errors will throw exceptions that you can catch. - translates unhandled exceptions into 'normal' JSON-responses with the correct HTTP-STATUS - translates unknown routes/URL's and methods into 'normal' 403 and 404 JSON-responses - CLI support to accept and protect for instance cronjob calls from the server - Middleware for database optimisation and memcache support - Query caching (using APCu), (*2)
Very simple to use, just use the SlimRestApi-class instead of the standard Slim App-class., (*3)
Edit the slim-rest-api.ini for correct (database) configuration., (*4)
Example index.php:, (*5)
<?php
declare(strict_types = 1);
namespace YourApi;
define("BASE_PATH", dirname(__FILE__));
require BASE_PATH . '/vendor/autoload.php';
use SlimRequestParams\BodyParameters;
use SlimRequestParams\QueryParameters;
use SlimRestApi\Middleware\CliRequest;
use SlimRestApi\Middleware\Cacheable;
use SlimRestApi\Middleware\ReadOnly;
use SlimRestApi\SlimRestApi;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class YourApi extends SlimRestApi
{
public function __construct()
{
// call parent ctor before anything else!
parent::__construct();
// Add a route
$this->get("/echo", function (
ServerRequestInterface $request,
ResponseInterface $response,
\stdClass $args)
: ResponseInterface
{
return $response->withJson(QueryParameters::get());
})
->add(new QueryParameters([
'{string:.{30}},the lazy fox',
'{mandatory_int:\d{1,10}}',
'{char:[[:alnum:]]{1}},a',
'{int:\int},1',
'{bool:\bool},true',]))
->add(new ReadOnly);
}
}
// instantiate and run
(new YourApi)->run();
Start the PHP server:, (*6)
php -S localhost:8000
Open this URL's in your browser (see what happens):, (*7)
http://localhost:8000/echo http://localhost:8000/echo?mandatory_int=1 http://localhost:8000/echo?mandatory_int=1&bool=false
Run composer install to add slim-rest-api your vendor folder., (*8)
{
"require":
{
"patricksavalle/slim-rest-api": "^1.0"
}
}
Include in your source., (*9)
<?php require './vendor/autoload.php';
Copy the slim-rest-api.ini file to the project-root and edit (put in your settings), (*10)
This packages comes with a minimum of (optional) helpers and middleware., (*11)
See: https://github.com/patricksavalle/slim-request-params, (*12)
use SlimRequestParams\BodyParameters; use SlimRequestParams\QueryParameters;
Sets route to read-only, optimising the database engine, adding a layer of robustness by preventing unwanted updates to the database., (*13)
use SlimRestApi\Middleware\ReadOnly; $YourApp->get(...)->add( new ReadOnly );
If you use other middleware (e.g. authentication) that needs write-access, chain them AFTER this method, like so, (*14)
use SlimRestApi\Middleware\ReadOnly;
$YourApp->get(...)
->add( new ReadOnly )
->add( new Authentication )
-> ...
Very usefull for functions that should not be exposed over HTTP (such as cronjob callbacks or configuration methods). For examples see: https://github.com/pavlakis/slim-cli, (*15)
use SlimRestApi\Middleware\CliRequest; $YourApp->get(...)->add( new CliRequest );
Makes database access as simple as possible. Automatically handles prepared-statement usage. Adds supersimple transaction support., (*16)
use SlimRestApi/Db;
$obj = Db::transaction(function(){
$obj = Db::execute("SELECT * FROM yourtable LIMIT 1")->fetch();
$obj->some_field = 'changed';
Db::update($obj);
return $obj;
});
All PDO-statements are accessible through the Db-singleton (magic method). To prevent warnings use:, (*17)
/** @noinspection PhpUndefinedMethodInspection */
Easy query caching (using APCu)., (*18)
Makes INI's as simple as possible. Looks for a 'slim-rest-api.ini' file in the webroot, see project for axeample., (*19)
Uue SlimeRestApi/Ini;
$value = Ini::get('key');
Provides a memcached version of call_user_func_array(). Use only for true functions (i.e. code without side-effects so the result depends only on the function-argument)., (*20)
use SlimRestApi/Memcache; $value = Memcache::call_user_func_array(...);
These functions actually uses APCu as caching engine., (*21)
Fork it., (*22)
Production-grade REST-API App-class for PHP SLIM
MIT