Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Mar 8, 2013

/{controllerName}/{actionName}

Bad, very bad decisions.

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

@ellisgl

This comment has been minimized.

Copy link

commented Apr 16, 2013

@Elfet: I would like to see yours.

@sebastian-marinescu

This comment has been minimized.

Copy link

commented May 27, 2014

@Elfet: I too 👍

@AchrafSoltani

This comment has been minimized.

Copy link

commented Jun 4, 2015

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
You can’t perform that action at this time.