Skip to content

Instantly share code, notes, and snippets.

@8ig8
Last active December 15, 2015 12:14
Show Gist options
  • Save 8ig8/15d98526466f527bee3c to your computer and use it in GitHub Desktop.
Save 8ig8/15d98526466f527bee3c to your computer and use it in GitHub Desktop.
Simple PHP view class
<?php
// usage
$view = new View( 'template.php' );
$view->title = 'My Title';
$view->text = 'Some text';
$nav = new View( 'nav.php' );
$nav->links = array( 'http://www.google.com' => 'Google', 'http://www.yahoo.com' => 'Yahoo' );
$view->nav = $nav;
echo $view;
<?php
<html>
<head>
<title><?php echo $this->title ?></title>
</head>
<body>
<?php echo $this->nav ?>
<?php echo $this->escape( $this->text ) ?>
</body>
</html>
//nav.phtml
<?php foreach( $this->links as $url => $link ): ?>
<a href="<?php echo $url ?>"><?php echo $link ?></a>
<?php endforeach ?>
<?php
// http://stackoverflow.com/a/529923
class View {
protected $filename;
protected $data;
function __construct( $filename ) {
$this->filename = $filename;
}
function escape( $str ) {
return htmlspecialchars( $str ); //for example
}
function __get( $name ) {
if( isset( $this->data[$name] ) ){
return $this->data[$name];
}
return false;
}
function __set( $name, $value ) {
$this->data[$name] = $value;
}
function render() {
ob_start();
include( $this->filename );
return ob_get_clean();
}
function __toString() {
return $this->render();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment