Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple HTTP REST Controller wrapper for Silex based on https://gist.github.com/igorw/3646064
<?php
namespace Controller;
class HomeController
{
public function getAction($app)
{
return 'Hello!';
}
}
<?php
chdir(__DIR__);
require('../vendor/autoload.php');
// Loader for app classes
spl_autoload_register(function($class) {
$file = str_replace('\\', '/', $class);
if(is_file(__DIR__ . '/' . $file . '.php')) {
require __DIR__ . '/' . $file . '.php';
}
});
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
// Disable libxml errors
libxml_use_internal_errors(true);
date_default_timezone_set('GMT');
$app = new Silex\Application();
$app['debug'] = true;
$app['pdo'] = $app->share(function() {
return new PDO(
'mysql:dbname=____;host=localhost',
'root',
'',
array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
)
});
$app->before(function (Request $request) {
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request = new ParameterBag(is_array($data) ? $data : array());
}
});
// https://gist.github.com/davedevelopment/4151421
// https://gist.github.com/ziadoz/7323919
// https://gist.github.com/igorw/3646064
$app->get('/{controllerName}', function ($controllerName) use ($app) {
$controllerName = ucfirst($controllerName);
$class = "Controller\\{$controllerName}Controller";
$method = strtolower($app['request']->getMethod());
if ( ! class_exists($class)) {
$app->abort(404);
}
$reflection = new ReflectionClass($class);
if ( ! $reflection->hasMethod($method . 'Action')) {
$app->abort(404);
}
$controller = new $class();
$result = $controller->{$method . 'Action'}($app);
if($result instanceof Response) {
return $result;
}
if($result instanceof JsonResponse) {
return $result;
}
if(is_int($result)) {
return $app->abort($result); // , $message, $headers
}
if(is_array($result)) {
$view = new View("$controllerName/$method");
$view->set($result);
return $view;
}
return $result;
})
->value('controllerName', 'home');
$app->finish(function (Request $request, Response $response) {
//print 'after';
});
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.