a SensioLabs Product

The PHP micro-framework
based on the Symfony Components

This is documentation is for Silex 2.0. Switch to Silex 1.3 documentation.

Questions & Feedback

License

Creative Commons License Silex documentation is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

Organizing ControllersΒΆ

When your application starts to define too many controllers, you might want to group them logically:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// define controllers for a blog
$blog = $app['controllers_factory'];
$blog->get('/', function () {
    return 'Blog home page';
});
// ...

// define controllers for a forum
$forum = $app['controllers_factory'];
$forum->get('/', function () {
    return 'Forum home page';
});

// define "global" controllers
$app->get('/', function () {
    return 'Main home page';
});

$app->mount('/blog', $blog);
$app->mount('/forum', $forum);

// define controllers for a admin
$app->mount('/admin', function ($admin) {
    // recursively mount
    $admin->mount('/blog', function ($user) {
        $user->get('/', function () {
            return 'Admin Blog home page';
        });
    });
});

Note

$app['controllers_factory'] is a factory that returns a new instance of ControllerCollection when used.

mount() prefixes all routes with the given prefix and merges them into the main Application. So, / will map to the main home page, /blog/ to the blog home page, /forum/ to the forum home page, and /admin/blog/ to the admin blog home page.

Caution

When mounting a route collection under /blog, it is not possible to define a route for the /blog URL. The shortest possible URL is /blog/.

Note

When calling get(), match(), or any other HTTP methods on the Application, you are in fact calling them on a default instance of ControllerCollection (stored in $app['controllers']).

Another benefit is the ability to apply settings on a set of controllers very easily. Building on the example from the middleware section, here is how you would secure all controllers for the backend collection:

$backend = $app['controllers_factory'];

// ensure that all controllers require logged-in users
$backend->before($mustBeLogged);

Tip

For a better readability, you can split each controller collection into a separate file:

1
2
3
4
5
6
7
8
// blog.php
$blog = $app['controllers_factory'];
$blog->get('/', function () { return 'Blog home page'; });

return $blog;

// app.php
$app->mount('/blog', include 'blog.php');

Instead of requiring a file, you can also create a Controller provider.

This website is powered by Silex and Twig. The Silex logo is © 2010-2016 SensioLabs