Skip to content

Instantly share code, notes, and snippets.

@esfand
Forked from igorw/FooController.php
Created May 24, 2014 08:12
Show Gist options
  • Save esfand/e0a2ab0e9c10ade206d1 to your computer and use it in GitHub Desktop.
Save esfand/e0a2ab0e9c10ade206d1 to your computer and use it in GitHub Desktop.

Silex convention-based controllers

This example shows how you can easily load controllers by convention with silex. The following routes are all valid:

  • /
  • /index
  • /index/index
  • /foo
  • /foo/index
  • /foo/hello
  • /foo/hello?name=igorw

A possible extension to this would be passing the application to the controller as well, either to the constructor of the class, or to the method directly. Or using some kind of mapping (possibly with annotations) to inject specific services only.

{
"require": {
"silex/silex": "1.0.*"
},
"autoload": {
"psr-0": { "Foobar": "src" }
},
"minimum-stability": "dev"
}
<?php
// src/Foobar/Controller/FooController.php
namespace Foobar\Controller;
class FooController
{
public function helloAction($request)
{
return "Hello ".($request->get('name') ?: "World");
}
public function indexAction($request)
{
return "foo index";
}
}
<?php
// web/index.php
require __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/{controllerName}/{actionName}', function ($controllerName, $actionName) use ($app) {
$controllerName = ucfirst($controllerName);
$class = "Foobar\Controller\\{$controllerName}Controller";
$method = "{$actionName}Action";
if (!class_exists($class)) {
$app->abort(404);
}
$reflection = new ReflectionClass($class);
if (!$reflection->hasMethod($method)) {
$app->abort(404);
}
$controller = new $class();
return $controller->$method($app['request']);
})
->value('controllerName', 'index')
->value('actionName', 'index');
$app->run();
<?php
// src/Foobar/Controller/IndexController.php
namespace Foobar\Controller;
class IndexController
{
public function indexAction($request)
{
return "index index";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment