-
-
Save jmontoyaa/5796460 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"silex/silex": "1.0.*@dev" | |
}, | |
"autoload": { | |
"psr-0": { "Igorw": "src" } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// src/Igorw/FooController.php | |
namespace Igorw; | |
class FooController | |
{ | |
function getIndexAction() | |
{ | |
return 'get index'; | |
} | |
function getBarAction() | |
{ | |
return 'get bar'; | |
} | |
function postBarAction() | |
{ | |
return 'post bar'; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// web/index.php | |
require 'vendor/autoload.php'; | |
$app = new Silex\Application(); | |
$app['debug'] = true; | |
$app->mount('/', new Igorw\ReflectionControllerProvider('Igorw\FooController')); | |
$app->run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment