benrowe / properties
A simple runtime package for handling properties on a class
1.1.1
2018-06-05 21:21 UTC
Requires
- php: ~7.1
Requires (Dev)
- phpunit/phpunit: ~5.0
- scrutinizer/ocular: ~1.1
- squizlabs/php_codesniffer: ^2.3
README
Adds the ability to add properties to a class at runtime.
Install
Via Composer
$ composer require benrowe/properties
Usage
class Sample extends AbstractBase { public function __construct() { // do stuff $this->configureProperties(); // properties now available } /** * This method is automatically called by AbstractBase once * the constructor has finished executing */ public function configureProperties() { $this-> addProperty('simple') $this ->addProperty('complex', 'string', 'default value') ->setter(function($value) { return trim($value); }) ->getter(function($value) { return str_reverse($value); }) ->validate(function ($value) { return strlen($value) > 0; }); } } $sample = new Sample; $sample->simple = 'test'; $sample->undefined = 'newval'; // throws PropertyException "Undefined property 'undefined'" $sample->complex; // 'default value' $sample->complex = ''; // throws PropertyException "property 'complex' invalid value on set" $sample->complex = ' hello world'; echo $sample->complex; //'dlrow olleh';
Each property is defined programatically (at runtime), and requires the class to run this code (with a hook).
Each property can have a
- name:string
- data type(s): string
- validation: string|closure
- setter: closure
- getter:string
- default value (null): mixed
- value: mixed (depends on data type/validation/setter)
TODO
- add the ability for a setter to reject a value by throwing an exception
- build custom validation support for setting the value
- instead of providing a closure for the setter, provide a laravel style validation string.
- add a helper function to restrict the setter to a list of known values
$this->addProperty('key')->isIn(['foo', 'bar']);
Change log
Please see CHANGELOG for more information what has changed recently.
Testing
$ composer test
Contributing
Please see CONTRIBUTING and CONDUCT for details.
Security
If you discover any security related issues, please email ben.rowe.83@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.