Adds the ability to add properties to a class at runtime.
Via Composer
$ composer require benrowe/properties
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)
- 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']);
Please see CHANGELOG for more information what has changed recently.
$ composer test
Please see CONTRIBUTING and CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.