Skip to content

Instantly share code, notes, and snippets.

@igorw
Created September 5, 2012 22:13
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save igorw/3646064 to your computer and use it in GitHub Desktop.
Save igorw/3646064 to your computer and use it in GitHub Desktop.
Silex convention-based controllers

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";
}
}
@antonmedv
Copy link

/{controllerName}/{actionName}

Bad, very bad decisions.

If you want i show you how to use annotation controllers with Silex.

@ellisgl
Copy link

ellisgl commented Apr 16, 2013

@Elfet: I would like to see yours.

@sebastian-marinescu
Copy link

@Elfet: I too 👍

@achrafsoltani
Copy link

Hi,

I was looking for controller based routing for silex, then foudn some providers but I also wanted to have the service container directly injected into my controllers, so with this snippet I could implement such a provider, I hope it's working fine and I'm wondering if you guys can check it and improve it

https://github.com/AchrafSoltani/RoutingServiceProvider

Best Regards

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