Call smarty function to another function

108 views Asked by At

So I am using slim framework together with smarty and I don't want to repeat these lines of code:

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

As you can see I will have more function and will always include those lines. How can I transfer it to a function and just call it in my viewBooks function?

1

There are 1 answers

0
Davide Pastore On

You could create a hook for this:

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