Skip to content

Instantly share code, notes, and snippets.

@igorw
Last active December 11, 2015 01:38
Show Gist options
  • Save igorw/4524636 to your computer and use it in GitHub Desktop.
Save igorw/4524636 to your computer and use it in GitHub Desktop.
Convention-based Reflection Controller Provider for Silex.
{
"require": {
"silex/silex": "1.0.*@dev"
},
"autoload": {
"psr-0": { "Igorw": "src" }
}
}
<?php
// src/Igorw/FooController.php
namespace Igorw;
class FooController
{
function getIndexAction()
{
return 'get index';
}
function getBarAction()
{
return 'get bar';
}
function postBarAction()
{
return 'post bar';
}
}
<?php
// web/index.php
require 'vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->mount('/', new Igorw\ReflectionControllerProvider('Igorw\FooController'));
$app->run();
<?php
// src/Igorw/FooControllerProvider.php
namespace Igorw;
use Silex\Application;
use Silex\ControllerProviderInterface;
class ReflectionControllerProvider implements ControllerProviderInterface
{
private $class;
function __construct($class)
{
$this->class = $class;
}
function connect(Application $app)
{
$controllers = $app['controllers_factory'];
$reflection = new \ReflectionClass($this->class);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
$methodName = $method->getName();
if (!preg_match('/^(get|post|put|delete|match)(.+)Action$/', $methodName, $matches)) {
continue;
}
list($_, $httpMethod, $path) = $matches;
$path = $this->adjustPath($path);
$controllers->$httpMethod($path, $this->class.'::'.$methodName);
}
return $controllers;
}
private function adjustPath($path)
{
$path = lcfirst($path);
$path = ('index' === $path) ? '' : $path;
$path = '/'.$path;
return $path;
}
}
@rybakit
Copy link

rybakit commented Jan 19, 2013

@igorw
Copy link
Author

igorw commented Jan 23, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment