Skip to content

Instantly share code, notes, and snippets.

@ScreamingDev
Last active December 22, 2015 20:29
Show Gist options
  • Select an option

  • Save ScreamingDev/6526865 to your computer and use it in GitHub Desktop.

Select an option

Save ScreamingDev/6526865 to your computer and use it in GitHub Desktop.
Wohoo. Templates and Cache :)
<?php
class Cache {
protected $_scope;
public function __construct($scope = null, $lifetime = 3600) {
if (null === $scope) $scope = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'mikeCache_' . md5(__FILE__) . DIRECTORY_SEPARATOR;
if (!is_dir($scope)) mkdir($scope, 0777, true);
$this->_scope = rtrim($scope, DIRECTORY_SEPARATOR);
$this->_lifetime = $lifetime;
}
protected function _isValidKey($key) {
if (false !== strpos($key, "\\") || false !== strpos($key, "/")) {
throw new Exception('Who do you want to hack?');
return false;
}
return true;
}
public function __set($key, $content) {
if ($this->_isValidKey($key)) \file_put_contents($this->_scope . DIRECTORY_SEPARATOR . $key, serialize($content));
}
public function __get($key) {
$filename = $this->_scope . DIRECTORY_SEPARATOR . $key;
if (!$this->_isValidKey($key)) || !file_exists($filename) || filectime($filename) + $this->_lifetime < time()) return null;
return unserialize(\file_get_contents($filename));
}
}
<?php
// oh no a visitor... do I have to do something?
$cache = new Cache();
if (!$cache->welcome)
{ // yes i have to -.-
$welcome = new View('welcome.phtml', ['name' => 'Tom']);
$cache->welcome = $welcome;
}
$cache->welcome->dispatch();
<?php
class View extends \ArrayObject {
protected $_fileName;
public function __construct($fileName, $data = array())
{
if (!stream_resolve_include_path($fileName)) throw new \ArgumentException("File $fileName not found.");
$this->_fileName = $fileName;
parent::__construct((array) $data);
}
public function getFileName() {
return $this->_fileName;
}
public function __toString() {
ob_start();
$this->dispatch();
return ob_get_clean();
}
public function dispatch() {
extract($this->getArrayCopy());
include $this->getFileName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment