Last active
December 15, 2015 12:14
-
-
Save 8ig8/15d98526466f527bee3c to your computer and use it in GitHub Desktop.
Simple PHP view class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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