Justin
Justin

Reputation: 4263

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

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.

Upvotes: 7

Views: 9015

Answers (1)

igorw
igorw

Reputation: 28249

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.

Upvotes: 15

Related Questions