Skip to content

Instantly share code, notes, and snippets.

@alexbilbie
Last active August 29, 2015 14:11
Show Gist options
  • Save alexbilbie/4d3e949dadfe34a65d74 to your computer and use it in GitHub Desktop.
Save alexbilbie/4d3e949dadfe34a65d74 to your computer and use it in GitHub Desktop.
StackPHP basic API versioned routes example

Setup

$ composer install
$ php -S localhost:8000

Version 1.0 call:

curl -X "GET" "http://localhost:8000/index.php/foo" -H "Accept: 1.0"

Version 2.0 call:

curl -X "GET" "http://localhost:8000/index.php/foo" -H "Accept: 2.0"

Any version call:

curl -X "GET" "http://localhost:8000/index.php/bar" -H "Accept: 1.0"

{
"require": {
"alexbilbie/proton": "~1.0",
"stack/builder": "~1.0"
}
}
<?php
use Orno\Http\JsonResponse;
use Proton\Application;
use Stack\Builder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
include('vendor/autoload.php');
class A {
public function run()
{
return new JsonResponse(['foo' => 'bar', 'class' => __CLASS__]);
}
}
class B {
public function run()
{
return new JsonResponse(['bar' => 'foo', 'class' => __CLASS__]);
}
}
class C {
public function run()
{
return new JsonResponse(['foobar' => 'barfoo', 'class' => __CLASS__]);
}
}
class ApiVersionMiddleware implements HttpKernelInterface
{
protected $app;
public function __construct(HttpKernelInterface $app)
{
$this->app = $app;
}
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
$version = $request->headers->get('Accept', '1.0');
$refObject = new \ReflectionObject($request);
$refProperty = $refObject->getProperty('pathInfo');
$refProperty->setAccessible(true);
$refProperty->setValue($request, sprintf('/%s%s', $version, $request->getPathInfo()));
return $this->app->handle($request, $type, $catch);
}
}
$proton = new Application();
$container = $proton->getContainer();
$container->add('A', function () { return new A(); });
$container->add('B', function () { return new B(); });
$container->add('C', function () { return new C(); });
$router = $proton->getRouter();
$router->addRoute('GET', '/1.0/foo', 'A::run'); // version 1.0 of API
$router->addRoute('GET', '/2.0/foo', 'B::run'); // version 2.0 of API
$router->addRoute('GET', '/{version:[0-9].[0-9]}/bar', 'C::run'); // all API versions
$stack = new Builder();
$stack->push('ApiVersionMiddleware');
$stackedApp = $stack->resolve($proton);
$response = $stackedApp->handle(Request::createFromGlobals($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER));
$response->send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment