Skip to content

Instantly share code, notes, and snippets.

@masarugen
Created August 28, 2012 02:39
Show Gist options
  • Save masarugen/3494441 to your computer and use it in GitHub Desktop.
Save masarugen/3494441 to your computer and use it in GitHub Desktop.
/**
* Handle dynamic method calls on the model.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
$meta = array('key', 'table', 'connection', 'sequence', 'per_page', 'timestamps');
// If the method is actually the name of a static property on the model we'll
// return the value of the static property. This makes it convenient for
// relationships to access these values off of the instances.
if (in_array($method, $meta))
{
return static::$$method;
}
$underscored = array('with', 'find');
// Some methods need to be accessed both staticly and non-staticly so we'll
// keep underscored methods of those methods and intercept calls to them
// here so they can be called either way on the model instance.
if (in_array($method, $underscored))
{
return call_user_func_array(array($this, '_'.$method), $parameters);
}
// First we want to see if the method is a getter / setter for an attribute.
// If it is, we'll call the basic getter and setter method for the model
// to perform the appropriate action based on the method.
if (starts_with($method, 'get_'))
{
return $this->get_attribute(substr($method, 4));
}
elseif (starts_with($method, 'set_'))
{
$this->set_attribute(substr($method, 4), $parameters[0]);
}
// Finally we will assume that the method is actually the beginning of a
// query, such as "where", and will create a new query instance and
// call the method on the query instance, returning it after.
else
{
return call_user_func_array(array($this->query(), $method), $parameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment