Skip to content

PHP Create Action

Martin René Sørensen edited this page Sep 30, 2020 · 1 revision

To create a controller action you need to create a class, in the namespace: App\Actions and have the class implement the interface: App\Interfaces\ActionInterface.

Example:

namespace App\Actions;

use App\Interfaces\ActionInterface;
use Nyholm\Psr7\Stream;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Slim\Interfaces\RouteCollectorInterface;

class Test implements ActionInterface
{

    /**
     * @inheritDoc
     */
    public static function register(RouteCollectorInterface $routeCollector): void
    {
        // This method should register the route in the RouteCollectorInterface
        $routeCollector->map(['POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'GET'], '/test', static::class);
    }

    /**
     * @inheritDoc
     */
    public function __invoke(RequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        return $response->withStatus(204)->withBody(Stream::create(''));
    }
}

It is also possible to register middleware on the Action by adding it to the created route instance:

    public static function register(RouteCollectorInterface $routeCollector): void
    {
        // This method should register the route in the RouteCollectorInterface
        $routeCollector->map(['POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'GET'], '/test', static::class)
            ->add(MyAwesomeMiddleware::class);
    }

The __invoke method is the method that will be run when the action is matched by a HTTP request.