How to access the Altorouter instance in my views

155 Views Asked by At

I'm new to php, I would like to have access to the $router instance in my views so that I can use the route names with $router->generate() in the view but I don't know how to do it? I use Altorouter like this:

Index.php

$router = new AltoRouter();
$router->map( 'GET', '/post/[:id]/', 'PostController#find' );
$match = $router->match();

        if ($match === false) {
            throw new \Exception($error->404());
        } else {
            list($controller, $action) = explode('#', $match['target']);
            if (is_callable(array($controller, $action))) {
                $obj = new $controller();
                call_user_func_array(array($obj, $action), array($match['params']));
            } else {
                throw new \Exception($error->500());
            }
        }

PostController.php

public function find($args)
    {
        $post = $this->PostModal->find($args[id]);
        // View
        View::render('post/show', compact('post'));
    }

My class View.php which manages the views

public static function render(string $path, array $variables = [])
    {
        extract($variables);
        ob_start();

        require 'views/' . $path . '.html.php';
        $pageContent = ob_get_clean();

        require 'views/layouts/layout.html.php';
    }
1

There are 1 best solutions below

0
KingKorg On

If you have the same problem as me, I resolved by adding

global $router;

in the render