benrowe/properties

A simple runtime package for handling properties on a class

0.1.2 2017-03-27 06:14 UTC

README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

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

  • build custom validation support for setting the value

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.