Home » Php » How do you setup the controller in a Silex PHP Framework project?

How do you setup the controller in a Silex PHP Framework project?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I can’t seem to get anything to work past the root path so far:

Do you put all your controller calls in the app.php file?

$app->get('/', function ($id) {
  ...
});

$app->get('/about', function ($id) {
  ...
});

Or do you put them in separate files?
So far the root get method works fine and renders a twig template, but anything past that does nothing.

How to&Answers:

Silex is a microframework. It gives you the ability to define your application within a single file. But that does not mean you have to.

What I usually do is define all the controllers in one app.php file, but extract re-usable parts into classes within the src directory, for example src/ProjectName/SomeClass.php, which can be autoloaded and also unit tested.

Now, if the amount of controllers grows, you can split up your application into “modules” and mount them under your main application (for example, mount an admin panel under /admin). Silex supports mounting, like so:

require_once __DIR__.'/silex.phar';

$app = new Silex\Application();

$app->mount('/admin', new Silex\LazyApplication(__DIR__.'/admin.php'));

For more details on mounting, check out Reusing applications from the Silex documentation.