Skip to content

Instantly share code, notes, and snippets.

@petterthowsen
Last active October 15, 2021 22:11
Show Gist options
  • Save petterthowsen/10b97040f39d4279f9a24fa5571665c9 to your computer and use it in GitHub Desktop.
Save petterthowsen/10b97040f39d4279f9a24fa5571665c9 to your computer and use it in GitHub Desktop.
Super simple PHP Template Class
<?php
namespace ThowsenMedia;
/**
* A Simple View/Template class that can process includes.
*
* new View('template-file', ['variable' => 'hello, world!'])
*
* Templates are just regular PHP Files.
* The $this variable is bound to the View instance.
*
* $this->include('partial') includes another view.
*
* the static::$viewsDirectory is the root directory where views are stored.
*
* all views are included with '.php' added.
*
*
* @author Petter Thowsen<petter@thowsenmedia.com>
* @license MIT
*/
class View
{
public static $viewsDirectory = __DIR__ .'/views';
private $_file;
public $_variables = [];
/**
* @var array
*/
private $errors = [];
public function __construct(string $file, array $variables = [])
{
$this->_file = static::$viewsDirectory .'/' .$file .'.php';
$this->_variables = $variables;
}
public static function make(string $file, array $variables = []): View
{
return new static($file, $variables);
}
private function include(string $file, array $variables = [])
{
return static::make($file, $variables)->render();
}
public function render()
{
extract($this->_variables);
ob_start();
include $this->_file;
return ob_get_clean();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment