首页 > 解决方案 > 将树枝传递给 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 中的函数。

标签: phptwigaltorouter

解决方案


您将变量传递closures给函数,use例如

$router->map( 'GET', '/[*:id]', function ($id) use ($twig) {
    handleRoutes($id, $twig);
});

推荐阅读