Anonymous controller and trait for Slim3 with PHP7
MIT License
Anonymous controller and trait for Slim3 with PHP7. We can use anonymous classes in PHP7. So I use anonymous classes instead of anonymous functions. Slim3 now supports PSR-7 interfaces for its Request and Response objects. And Slim3 uses extends objects, and use it in your anonymous functions.
But we use Request and Response object directly, so I try to use anonymous classes to write controller action logic and it is to be readability. read more
install via composer
composer require brtriver/slim3-controller
you can read example code.
sample code is blow:
use Brtriver\Controller\Controller;
$app->get('/hello/{name}', new class($app) extends Controller {
public function action($args)
{
return $this->render($this->container['greet'] . $args['name']);
}
});
If use Template engine (PHP or Twig etc...), a renderWithT method in Templatable trait is available:
use Brtriver\Controller\Controller;
use Brtriver\Controller\Templatable;
$app->get('/hello/{name}', new class($app) extends Controller {
use Templatable;
public function action($args)
{
return $this->renderWithT('web.html', ['name' => $args['name']]);
}
});
If use JSON response, a renderWithJson method in JsonResponse trait is available:
use Brtriver\Controller\Controller;
use Brtriver\Controller\JsonResponse;
$app->get('/json/{name}', new class($app) extends Controller {
use JsonResponse;
public function action($args)
{
return $this->renderWithJson(['name' => $args['name']]);
}
});
slim3-controller is licensed under the MIT license.