我有以下内容:
<?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');
}
?>
handleRoutes函数应该获取路由名称(如"about"或"contact"(并将其传递给树枝渲染器。然而,$trick在handleRoutes函数中不可用,我不知道如何正确地将其传递给对象。我试过了:
function handleRoutes($name, $obj) {
echo $obj->render($name . '.twig');
}
$router->map( 'GET', '/[*:id]', function ($id) {
handleRoutes($id, $twig);
});
但是$trick也不能用于$router->映射中的函数。
使用函数use
向closures
传递变量,例如
$router->map( 'GET', '/[*:id]', function ($id) use ($twig) {
handleRoutes($id, $twig);
});