所以我使用slim framework和smarty,我不想重复这些代码:
require 'vendor/autoload.php';
require 'class.db.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/', 'viewBooks');
$app->run();
function viewBooks()
{
//Dont want to repeat this
require_once('smarty/libs/Smarty.class.php');
$temp = new SmartyBC();
$temp->template_dir = 'views';
$temp->compile_dir = 'tmp';
//Dont want to repeat this end
$db = new db();
$data = $db->select("books");
$temp->assign('book', $data);
$temp->display('index.tpl');
$db = null;
}
正如您所看到的,我将拥有更多功能,并且将始终包含这些线条。如何将其传输到函数并在我的viewBooks
函数中调用它?
答案 0 :(得分:0)
您可以为此创建hook:
<?php
$app->hook('slim.before.dispatch', function() use ($app) {
//Your repetitive code
require_once('smarty/libs/Smarty.class.php');
$temp = new SmartyBC();
$temp->template_dir = 'views';
$temp->compile_dir = 'tmp';
//Inject your $temp variable in your $app
$app->temp = $temp;
});
function viewBooks() use ($app){
$db = new db();
$data = $db->select("books");
//Use your injected variable
$app->temp->assign('book', $data);
$app->temp->display('index.tpl');
$db = null;
}