Last active
January 7, 2016 17:19
-
-
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`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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