Skip to main content
Go to homepage
Github

Controllers

Controllers are one of the different ways to organize your project, with controllers you can centralize the request handling logic.

Create routes

To create a Controller, create a PHP file in the system/Controllers/ folder, for example: FooBar.php, then add the following content:

<?php namespace Controllers; class FooBar { public function hello($app, $params) { return 'Hello World'; } public function hundop($app, $params) { return 'Hundo P!'; } }

Then in system/main.php create a route pointing to the controller:

<?php $app->action('GET', '/hello', 'FooBar::hello'); $app->action('GET', '/100', 'FooBar::hundop');

It's also possible to add it to a subdirectory, for example system/Controllers/Foo/Bar/Baz.php, and add that to the content (don't forget to adjust the namespace):

<?php namespace Controllers\Foo\Bar; class Baz { public function say($app, $params) { return 'Hello World'; } }

Then add the route:

<?php $app->action('GET', '/say', 'Controllers\Foo\Bar\Baz::say');

Define the prefix for the controller namespaces

To avoid repeatedly writing the namespace if you have a long namespace, you can change the namespace prefix for subsequent routes, or routes by scope, example:

<?php $app->setNamespace('Controllers\\Foo\\Bar'); // system/Controllers/Foo/Bar/Baz.php $app->action('GET', '/', 'Baz::index'); $app->action('GET', '/create', 'Baz::create'); $app->action('GET', '/read', 'Baz::read'); $app->action('GET', '/update', 'Baz::update'); $app->action('GET', '/delete', 'Baz::delete'); // system/Controllers/Foo/Bar/Baz.php $app->setNamespace('Controllers\\Halloween\\Ghost\\'); // system/Controllers/Halloween/Ghost/Boo.php $app->action('GET', '/halloween/trick', 'Boo::trick'); $app->action('GET', '/halloween/treat', 'Boo::treat');

The Controllers folder is not mandatory; you can completely change the namespace, but to do so you will need to add the entry "psr-4": to composer.json, which currently should be:

... "autoload": { "psr-4": { "Commands\\": "system/Commands", "Controllers\\": "system/Controllers", "Models\\": "system/Models" } }, ...

Change it to:

... "autoload": { "psr-4": { "Commands\\": "system/Commands", "Controllers\\": "system/Controllers", "CustomFolder\\": "system/CustomFolder", "Models\\": "system/Models" } }, ...

Then configure it in system/main.php:

<?php $app->setNamespace('CustomFolder\\Foo\\Bar'); // system/CustomFolder/Foo/Bar/Baz.php $app->action('GET', '/', 'Baz::index'); $app->action('GET', '/create', 'Baz::create'); $app->action('GET', '/read', 'Baz::read'); $app->action('GET', '/update', 'Baz::update'); $app->action('GET', '/delete', 'Baz::delete'); // Restores the original prefix $app->setNamespace('Controllers'); // system/Controllers/Hello.php $app->action('GET', '/', 'Hello::index');