This site is built with Viewi itself. It is experimental and still in development. If you see any bugs please do not hesitate and open an issue or DM me on Twitter.

Guards and Middleware

In Viewi component you can set up a middleware(s) for your component. like this:

class ProtectedPage extends BaseComponent
{
    // declare static property "$_beforeStart"
    // and put Middleware class names inside of the array.
    public static array $_beforeStart = [MemberGuard::class];
// ...

Where MemberGuard is a class that implements Viewi\Components\Interfaces\IMiddleware and has a method run(callable $next);

Inside of that method do whatever you need, and if you want to continue with the component (or the next middleware) call $next().

For example:

use Viewi\Common\ClientRouter;
use Viewi\Components\Interfaces\IMiddleware;

class MemberGuard implements IMiddleware
{
    private ClientRouter $router;
    private bool $isAuthenticated = false;

    public function __construct(
        ClientRouter $clientRouter
    ) {
        $this->router = $clientRouter;
    }

    public function run(callable $next)
    {
        if ($this->isAuthenticated) {
            $next(); // continue with the component
        } else {
            // redirect to the login page
            $this->router->navigate("/login");
            // call $next(false) to do not continue with the component
            $next(false);
        }
    }
}