Skip to content

Instantly share code, notes, and snippets.

@satlavida
Created September 2, 2011 16:57
Show Gist options
  • Save satlavida/1189158 to your computer and use it in GitHub Desktop.
Save satlavida/1189158 to your computer and use it in GitHub Desktop.
Data Store in PHP
<?php
class DataStore
{
public function __call($methodName, $args) {
if (preg_match('~^(set|get)([A-Z])(.*)$~', $methodName, $matches)) {
$property = strtolower($matches[2]) . $matches[3];
if (!property_exists($this, $property)) {
throw new Exception("Error Processing Request",1);
}
switch($matches[1]) {
case 'set':
$this->checkArguments($args, 1, 1, $methodName);
return $this->set($property, $args[0]);
case 'get':
$this->checkArguments($args, 0, 0, $methodName);
return $this->get($property);
case 'default':
throw new Exception("Error Processing Request",1);
}
}
}
public function get($property) {
return $this->$property;
}
public function set($property, $value) {
$this->$property = $value;
return $this;
}
protected function checkArguments(array $args, $min, $max, $methodName) {
$argc = count($args);
if ($argc < $min || $argc > $max) {
throw new Exception("Error Processing Request",1);
}
}
}
class MyData extends DataStore
{
public $data;
public $name;
}
$test = new MyData;
$test->setData('Hello World')->setName('Satlavida');
print $test->getData()." ".$test->getName();
//Result "Hello World Satlavida"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment