Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading variables in templates

Currently I am doing it like this:

function load_template($script, $args){
  extract($args);
  require __DIR__ . '/templates/' . $script;
}

In my controller code:

// if home page was requested
load_template('home.php', array(
  'title'   => get_title(),
  'content' => get_content(),
  ...
));

The template is just a PHP script like

<!DOCTYPE html>
<html>
<head>
  <title> <?php echo $title; ?> </titlee>
...

I was wondering if it's possible to lazy load these variables somehow, so I don't actually run get_title() or get_content() until the template specifically requests the variable.

Could this be possible, without creating a template parser thingy? I'd really like to stick with simple .php scripts and html as templates.


In short, what I'm asking is if it's possible to auto-assign a value to a variable only when it's first requested.

$var = func();  // this should not run

if($var){       // now the code above should run:)
  echo $var;   // <- the value that was just assigned (don't run func() again)
} 
like image 874
Alex Avatar asked Nov 12 '22 05:11

Alex


1 Answers

In my opinion, if you do not wish to change your template to extract the variables, you can create for example an array that would know which variables each template needs.

You may consider a function (let's name it caller) into which you pass all parameters and the template name. The caller could choose which variables are required. This idea is like a factory class in oop.

I think there is no other way, but...

While inserting a template and use unexistent variable, a warning will be shown. You can make PHP to throw exceptions in warnings and then in try ... catch block parse it. I think it's too complicated and not worth effort.

EDIT

The third idea is to create objects instead of arrays. The object would keep all your $args variable. In your template just change <?php echo $title; ?> to <?php echo $argument_object->getTitle(); ?>, and code the getTitle() method. The getTitle(), as a method not a function, would then be run only on request.

like image 73
Voitcus Avatar answered Nov 14 '22 23:11

Voitcus