Skip to content

Instantly share code, notes, and snippets.

@zaak
Created July 5, 2020 15:02
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 zaak/0da7e490bb1c5312332b6544f0392b64 to your computer and use it in GitHub Desktop.
Save zaak/0da7e490bb1c5312332b6544f0392b64 to your computer and use it in GitHub Desktop.
<?php
/**
* View rendering logic.
*
* @author Pawel Wiaderny <pawel.wiaderny@gmail.com>
*/
class View
{
/**
* Extension used by template files.
*/
const EXTENSION = '.php';
/**
* The name of the view as a lowercase relative path in the Views root directory.
* @var string
*/
protected $name;
/**
* Data to be passed to the template.
*
* @var array
*/
protected $data = [];
/**
* Factory method.
*
* @param string $name
* @param array $data
* @return View
*/
public static function create(string $name, array $data = [])
{
return new View($name, $data);
}
/**
* View constructor.
*
* @param string $name
* @param array $data
*/
public function __construct(string $name, array $data = [])
{
$this->name = $name;
$this->data = $data;
}
/**
* Sets the value to be passed to the template.
*
* @param $name
* @param $value
* @return $this
*/
public function set(string $name, $value): self
{
$this->data[$name] = $value;
return $this;
}
/**
* Renders this view object.
*
* @return string
*/
public function render(): string
{
$viewPath = __DIR__.'/views/'.$this->name.self::EXTENSION;
if (!is_readable($viewPath)) {
throw new \RuntimeException(
sprintf(
"Requested view file not found: %s. Path used: %s",
htmlspecialchars($this->name),
htmlspecialchars($viewPath)
)
);
}
// Render and grab output.
ob_start();
extract($this->data);
include $viewPath;
return ob_get_clean();
}
public function __toString()
{
return $this->render();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment