将智能函数调用到另一个函数



所以我将纤薄的框架与smarty一起使用,我不想重复这些代码行:

require 'vendor/autoload.php';
require 'class.db.php';
SlimSlim::registerAutoloader();
$app = new SlimSlim();
$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函数中调用它?

你可以为此创建一个钩子:

<?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;
}

最新更新