Skip to content

Instantly share code, notes, and snippets.

@rohmann
Created October 2, 2013 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohmann/6795815 to your computer and use it in GitHub Desktop.
Save rohmann/6795815 to your computer and use it in GitHub Desktop.
<?php
class View {
public static function __callStatic($name,$parameters) {
try {
//Get template name from method call
$fname = TEMPLATES_DIR . implode('/', explode("_",$name) ).'.php';
//Ensure this template exists
if(file_exists($fname)) {
//Set default parameters
if(!isset($parameters[0]))
$parameters[0] = array();
if(!isset($parameters[1]))
$parameters[1] = true;
if(!isset($parameters[2]))
$parameters[2] = true;
//Get parameters
list($data,$echo,$extract) = $parameters;
//By default the context will be extracted. This can be overriden if the template needs direct access
if($extract)
extract($data);
ob_start();
include($fname);
$buffer = ob_get_clean();
//Function will always buffer and return, but can echoing can be disabled.
if($echo)
echo $buffer;
return $buffer;
}
else {
throw new \Exception( "View Template not found: $fname", 1);
}
}
catch (\Exception $e) {
trigger_error($e->getMessage() , E_USER_WARNING);
}
return false;
}
}
@rohmann
Copy link
Author

rohmann commented Oct 2, 2013

Usage:

View::admin_dashboard_widget( array( 'hello' => 'world' ) );

This loads templates/admin/dashboard/widget.php and creates a variable called $hello containing "world" ready for use in the template.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment