Skip to content

Instantly share code, notes, and snippets.

@z1nkum
Last active October 23, 2015 15:47
Show Gist options
  • Save z1nkum/858f7f2161f23462a7be to your computer and use it in GitHub Desktop.
Save z1nkum/858f7f2161f23462a7be to your computer and use it in GitHub Desktop.
Class support unique param (id)
abstract class ObjectWithUniqueID {
public $id;
public static $registry = array();
public function getObjectById( $id ) {
if ( array_key_exists( $id, static::$registry ) ) {
return static::$registry[$id];
} else return null;
}
}
class ClientUniq extends ObjectWithUniqueID {
public $agreements = array();
public static $registry = array();
protected function __construct( $client_id, $client_name, $client_source ) {
$this->id = $client_id;
$this->client_name = $client_name;
$this->client_source = $client_source;
static::$registry[$client_id] = $this;
}
public static function getOrCreate( $client_id, $client_name, $client_source ) {
$obj = static::getObjectById($client_id);
if ( $obj === null ) {
return new ClientUniq($client_id, $client_name, $client_source);
} else return $obj;
}
}
/* Usage
$a = ClientUniq::getOrCreate('1', 'test1', 'mysource');
array_push($a->agreements, 1);
$b = ClientUniq::getOrCreate('2', 'test2', 'mysource');
array_push($b->agreements, 2);
$c = ClientUniq::getOrCreate('2', 'test2', 'mysource');
array_push($c->agreements, 3);
var_dump(ClientUniq::$registry);
// a - object with agreement list [1]
// b and c - reference to the same object, and it has agreement list [2,3]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment