Skip to content

Instantly share code, notes, and snippets.

@madfriend
Created April 29, 2012 21:27
Show Gist options
  • Save madfriend/2553346 to your computer and use it in GitHub Desktop.
Save madfriend/2553346 to your computer and use it in GitHub Desktop.
PHP 5.4 Pattern Traits
<?php
namespace traits;
trait Singleton {
// Для тех, кто не предусмотрел конструктор в классе
private function __construct() {
}
public static function getInstance() {
static $_instance = NULL;
$class = __CLASS__;
return $_instance ?: $_instance = new $class;
}
public function __clone() {
trigger_error('Cloning '.__CLASS__.' is not allowed.', E_USER_ERROR);
}
}
trait Prototype {
private
$_props = array(),
$_methods = array();
function &__get($name) {
if (array_key_exists($name, $this->_props )) {
return $this->_props[$name];
}
elseif (array_key_exists($name, $this->_methods )) {
return $this->_methods[$name];
}
return null;
}
function __set($name, $value) {
if (is_object($value) && is_callable($value)) {
if (!array_key_exists($name, $this->_methods)) {
$this->_methods[$name] = array();
}
if($value instanceof \Closure) {
$value = $value->bindTo($this);
}
$this->_methods[$name][] = $value;
}
else {
$this->_props[$name] = $value;
}
}
function __call($name, $args = array()) {
if (array_key_exists($name, $this->_methods)) {
$methods = $this->_methods[$name];
if (is_array($methods)) {
foreach($methods as $method) {
if(!is_null($result = call_user_func_array($method, $args))) {
return $result;
}
}
}
}
return null;
}
}
}
@madfriend
Copy link
Author

Example:

class MyAwesomeClass {
  use traits\Singleton; // now __construct is private, getInstance should be used instead
  private function __construct($foo, $bar) { // overriding
    echo "$foo is $bar";
  } 
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment