2015-06-12 150 views
0

所以我用纖細的框架,智者在一起,我不想再重複這些代碼: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

你可以爲此創建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; 
}