Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Last active December 16, 2016 12:22
Show Gist options
  • Save Lewiscowles1986/ee8d196b38996267c98c33449885dc4e to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/ee8d196b38996267c98c33449885dc4e to your computer and use it in GitHub Desktop.
PHP Design notes
<?php
interface IdentifiableInterface {
public function identify() : string;
}
interface HashableInterface {
public function getHash(IdentifiableInterface $obj) : string;
}
interface PersistableInterface {
public function persist();
}
interface RestorableInterface {
public function restore(string $pk);
}
interface PersistableRestorableInterface extends PersistableInterface, RestorableInterface {
}
interface CodecInterface {
public function encode($in);
public function decode($in);
}
interface StorageInterface {
public function put(string $hash, $object);
public function get(string $hash);
}
final class PhpSerializerCodec implements CodecInterface {
public function encode($in) {
return serialize($in);
}
public function decode($in) {
return unserialize($in);
}
}
final class ApcStorage implements StorageInterface {
public function __construct(CodecInterface $codec) {
$this->_codec = $codec;
}
public function put(string $hash, $object) {
apc_store($hash, $this->_codec->encode($object));
}
public function get(string $hash) {
return $this->_codec->decode(apc_fetch($hash));
}
}
final class ClassHasher implements HashableInterface {
public function getHash(IdentifiableInterface $object) {
return sprintf("%s%s", get_class($object), $object->identify());
}
}
final class Pk implements IdentifiableInterface {
protected $_value;
public function __construct(string $pk) {
$this->_value = $pk;
}
public function identify() : string {
return $this->_value;
}
}
final class MyClassC implements PersistableRestoreableInterface, IdentifiableInterface {
protected $_hasher;
protected $_storage;
public $id;
public function __construct(HashableInterface $hasher, StorageInterface $storage) {
$this->_hasher = $hasher;
$this->_storage = $storage;
}
public function persist() {
$this->_storage->put($this->hasher->getHash($this), $this);
}
public function restore(string $pk='') {
return $this->_storage->get(
$this->hasher->getHash(
( (strlen($pk)>0) ? new Pk($pk) : $this )
)
);
}
public function identify() : string {
return $this->id;
}
}
<?php
class MyClassA {
public $_id;
public function persist() {
apc_store(get_class($this) . $this->id, serialize($this));
}
public static function restore($id) {
return unserialize(apc_fetch(get_class($this) . $id));
}
}
class MyClassB {
public $_id;
public function persist() {
apc_store(get_class($this) . $this->id, serialize($this));
}
public static function restore($id) {
return unserialize(apc_fetch(get_class($this) . $id));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment