Skip to content

Instantly share code, notes, and snippets.

@TorbenL
Created January 7, 2014 16:16
Show Gist options
  • Save TorbenL/8301740 to your computer and use it in GitHub Desktop.
Save TorbenL/8301740 to your computer and use it in GitHub Desktop.
super simple php view class :-)
<?php
class MyClass extends TlView
{
public function __construct()
{
// optional
$this->setViewPath('/');
// optional
$this->setViewFilename('standard-template');
// optional
$this->setViewGlobalVars(array(
'time' => date('H:i'),
'day' => date('d.m.Y')
));
}
public function doSomething($firstname, $lastname)
{
$this->view('my-view', array(
'firstname' => $firstname,
'lastname' => $lastname
));
}
}
<?php
if(!class_exists('TlView'))
{
class TlView
{
private $path = '', $file = '', $filename = '';
private $vars = array();
public function __construct()
{
// nothing to do
}
protected function setViewPath($path)
{
$this->path = $path;
}
protected function setViewFilename($filename)
{
$this->filename = $filename;
}
protected function setViewGlobalVars($vars)
{
$this->vars = $vars;
}
protected function view($filename = '', $vars = array(), $return = false)
{
if(empty($filename))
$filename = $this->filename;
$this->file = $this->path.str_replace('.php', '', $filename).'.php';
if(!file_exists($this->file))
$this->file = rtrim(realpath(dirname(__FILE__)), '/').'/'.$this->file;
if(!file_exists($this->file))
{
$msg = '<pre>could not find template file <em>'.$this->file.'</em></pre>';
if(!$return)
echo $msg;
return $msg;
}
ob_start();
if(count($this->vars))
$vars = array_merge($this->vars, $vars);
if(count($vars))
extract($vars);
include($this->file);
$output = ob_get_contents();
ob_end_clean();
if(!$return)
echo $output;
return $output;
}
}
}
<?php
require_once('class.tl-view.php');
require_once('class.my-class.php');
$myClass = new MyClass();
$myClass->doSomething('Torben', 'Leuschner');
<p>
Hello, my name is <?= $firstname; ?> <?= $lastname; ?>!
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment