A managed system to allow for more traditional setters and getters on classes, including validation and type hinting
PHP
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src
tests
.editorconfig
.gitattributes
.gitignore
.scrutinizer.yml
.styleci.yml
.travis.yml
CHANGELOG.md
CONDUCT.md
CONTRIBUTING.md
LICENSE.md
README.md
composer.json
phpunit.xml.dist

README.md

Properties

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

  • 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.