Skip to content

Instantly share code, notes, and snippets.

@lwiesel
Last active January 7, 2016 17:19
Show Gist options
  • Select an option

  • Save lwiesel/8c2155f1492815b23200 to your computer and use it in GitHub Desktop.

Select an option

Save lwiesel/8c2155f1492815b23200 to your computer and use it in GitHub Desktop.
A PHP trait that adds to each attribute methods `getXxx`, `setXxx`, `isXxx` and `hasXxx`
<?php
namespace Domain\Model;
/**
* Behavior for parameters classes
*
* For a given attribute, it will add methods `getXxx`, `setXxx`, `isXxx` and `hasXxx`
* ex:
* an attribute `$foo` will be settable with `setFoo('bar')`
* and will be gettable with `getFoo()`, `isFoo()` or `hasFoo()`
*/
trait ParameterContainerTrait
{
/**
* @var mixed
*/
protected $parameter;
/**
* @param $method
* @param $parameters
*
* @return mixed
* @throws \Exception
*/
function __call($method, $parameters) {
$parts = preg_split("/((?<=[a-z])(?=[A-Z])|(?=[A-Z][a-z]))/", $method);
$verb = $parts[0];
$attribute = mb_strtolower($parts[1]);
switch ($verb) {
case 'get':
case 'is':
case 'has':
return $this->$attribute;
break;
case 'set':
$this->$attribute = $parameters[0];
break;
default:
throw new \Exception(sprintf('Method %s not implemented', $method));
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment