php - 将树枝传递给 altorouter 中的控制器功能
问题描述
我有以下内容:
<?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”)并将其传递给 twig 渲染器。但是, $twig 在 handleRoutes 函数中不可用,我不知道如何正确地将对象传递给它。我试过了:
function handleRoutes($name, $obj) {
echo $obj->render($name . '.twig');
}
$router->map( 'GET', '/[*:id]', function ($id) {
handleRoutes($id, $twig);
});
但是随后 $twig 也不能用于 $router->map 中的函数。
解决方案
您将变量传递closures
给函数,use
例如
$router->map( 'GET', '/[*:id]', function ($id) use ($twig) {
handleRoutes($id, $twig);
});
推荐阅读
- python - 如何使用python有效地填充“缺失时间模式”和“填充它们”具有特定值?
- java - 如何修复“索引 10 处的预期方案特定部分:类路径:”在 Cucumber-Java 中运行功能文件时出错
- mysql - 在虚拟列上创建 mysql 索引的问题
- css - 无法在 Oxygen 中生成的 PDF 输出中的表格单元格内打破一串符号
- c# - 您如何验证从主应用程序启动的应用程序中的令牌是否正确?
- python - 如何根据另一个列表的排序重新排序列表?
- python-3.x - 使用嵌套for循环时,如果嵌套循环中没有项目触发if语句,如何完成动作
- angular - 如何在 rxjs 6.4.0 Angular 中替换 flatMap 和 mergeMap
- r - 如何将过滤后的文件保存在函数中?
- kotlin - 给定列表列表,如何获取单个唯一的项目列表