如果我想从功能中分离出路线,那么最好的方法仍然需要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(
........
));
}
}
答案 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
咳嗽。