SLIM使用TWIG从功能中分离出路由

时间:2014-06-27 05:42:09

标签: php twig slim

如果我想从功能中分离出路线,那么最好的方法仍然需要use($app,$twig)

$app->get('/app(/:date(/:time))', function ($date = null,$time = null) use ($app,$twig)     {       
    //do some stuff using TWIG
}); 
 $app->run();

新路线,功能function app(...

$app->get('/app(/:date(/:time))', 'app');

编辑1 - 接下来尝试使用一个类给出一个`Undefined variable:twig'

$actions = new Actions($app, $twig);

$app->get('/app(/:date(/:time))', [$actions, 'app']);   
$app->run();


class Actions {

    protected $app, $twig;

    public function __construct($app, $twig) {
        $this->app  = $app;
        $this->twig = $twig;
    }

    public function app($date = null,$time = null) {
        // print_r($:date);

    //  get some data using date time

        $template = $twig->loadTemplate('template.php');
            echo $template->render(array(
            ........
            ));
    }
}

1 个答案:

答案 0 :(得分:3)

$appFunc = function () use ($app, $twig) ...
$app->get(..., $appFunc);

或:

class Actions {

    protected $app, $twig;

    public function __construct($app, $twig) {
        $this->app  = $app;
        $this->twig = $twig;
    }

    public function app() ...

}

$actions = new Actions($app, $twig);

$app->get(..., [$actions, 'app']);

或:

function app($app, $twig) {
    return function () use ($app, $twig) ...
}

$app->get(..., app($app, $twig));

咳嗽 global 咳嗽