-
-
Save igorw/4524636 to your computer and use it in GitHub Desktop.
{ | |
"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; | |
} | |
} |
You may omit unused $_
in ReflectionControllerProvider.php :
list($_, $httpMethod, $path)
-> list(, $httpMethod, $path)
@rybakit fair point, but let's be honest: that would make it look insane. like LISP unquoting. :D
sorry i am so ignorant but wondering if there was some context to it to read up
and also why everzet says something about Bulat's legacy
avalanche123 had similar code?
I see the mount option calls the connect passing the app and feeds inside the controller factory
the controller factory is used to invoke the methods of the class in turn
I see that we need to add checks for whether a style or interface has been followed on the http methods or at least throw exceptions if an action has not followed the pattern
My main question is why are we doing this, was the need to cluster controller action providers that prompt you for this? Say you want to dynamically change the controller action provided on certain endpoint according to certain input? What is your use case? Just curious as it is very interesting.
@igorw thanks in advance for your response
By the way, @cordoval: @avalanche123 had MicroKernelBundle.
Nice! Glad to see our with Bulat legacy lives :)