Controllers
Route and other (non-template) Controllers should go in app/Controllers
. If you're familiar with MVC frameworks sunch as Laravel and Symfony, then these should behave pretty much as you would expect.
For info on WordPress template controllers, check here.
What are controllers for?
Controllers are classes where you put your route-level request handling logic. In practise, they coral together http or other parameters and inputs, call the database layer to grab or save data via Models, and organise the results into something for the view layer to present back to the user. Forme uses the single action controller paradigm, leveraging the magic __invoke
method.
TIP
It's usually a good idea to keep Controllers fairly lean - if they get very long or if any of the logic starts looking heavy, have a think about whether it might be worth spinning things off into some kind of service or transformer class. The Controller's function is to orchestrate and organise rather than do too much heavy lifting. And if we're following SOLID principles, any class with more than a few methods, or very long methods, is a code smell!
Usage
Controllers should extend Forme\Framework\Controllers\AbstractController
and should have an __invoke
method which usually takes a PSR-7 request in the form of a Forme\Framework\Http\ServerRequest
object, although they can also accept an array of parameters.
Controllers should generally send back a PSR-7 response - strings and therefore view renders will be automatically converted to an HtmlResponse, arrays and any iterables will be turned into a JsonResponse.
// app/FooBarController.php
declare(strict_types=1);
namespace NameSpace\AppName;
use NameSpace\AppName\Core\View;
use Forme\Framework\Controllers\AbstractController;
use Psr\Http\Message\ServerRequestInterface;
final class FooBarController extends AbstractController
{
public function __construct(private View $view)
{
}
public function __invoke($request)
{
$context = $request->body();
return $this->view->render('single', $context);
}
}
Requests and Responses
Take a look at our pages on requests and responses for more information.
Code Generation
You can use the code generator to scaffold Controllers.
forme make controller FooBar
This will create a new controller called FooBarController
in the app/Controllers
folder.