I have the following:
<?php
require __DIR__ . "/vendor/autoload.php";
$router = new AltoRouter();
$loader = new Twig_Loader_Filesystem( array( 'views', 'views/pages', 'views/partial' ) );
$twig = new Twig_Environment( $loader, array(
'cache' => 'tmp',
'debug' => true,
'auto_reload' => true
) );
function handleRoutes($name) {
echo $twig->render($name . '.twig');
}
$router->map( 'GET', '/[*:id]', function ($id) {
handleRoutes($id, $twig);
});
$match = $router->match();
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
?>
The handleRoutes function is supposed to take the route name (such as "about" or "contact") and pass it to the twig renderer. However, $twig isn't available in the handleRoutes function and I don't know to how to pass it the object correctly. I tried:
function handleRoutes($name, $obj) {
echo $obj->render($name . '.twig');
}
$router->map( 'GET', '/[*:id]', function ($id) {
handleRoutes($id, $twig);
});
But then then $twig is also not available to the function in $router->map.
You pass variables towards closures
with the function use
e.g.
$router->map( 'GET', '/[*:id]', function ($id) use ($twig) {
handleRoutes($id, $twig);
});