selikhovleonid/accessors-trait

Trait for Property Accessors Generation

dev-master 2017-11-30 17:51 UTC

This package is not auto-updated.

Last update: 2024-04-28 02:43:00 UTC


README

Trait for Property Accessors Generation

Latest Unstable Version License PHP from Packagist

Installing

The minimum required PHP version is PHP 5.4. You will need Composer dependency manager to install this tiny tool.

php composer.phar require selikhovleonid/accessors-trait

Quick start

When the trait is used in a child class, it catches the calls of undeclared methods of this class. If the name of the invoked method matches the setProperty, getProperty or isPropertySet pattern and the target class has corresponding property, then this trait calls needed accessor as if it was declared directly in the child class.

You need just add one of the following tags to the PHPDoc block to mark property as accessible to the corresponding methods: @get, @set, @isset. The @accessors annotation marks property as full-accessible.

/**
 * Foo class description
 */
class Foo
{
    use \nadir2\tools\AccessorsTrait;

    /**
     * @var string Property description
     * @accessors
     */
    protected $property;

    /**
     * @var array Another property description
     * @get
     * @isset
     */
    private $anotherProperty = [];

    /**
     * This method sets value of 'another property'.
     * @param array $data Passed data.
     * @return self
     */
    public function setAnotherProperty(array $data)
    {
        $this->anotherProperty = $data;
        return $this;
    }
}

$foo = new Foo();

// The following code is valid
if (!$foo->isPropertySet()) {
    $foo->setProperty('bar');
    $bar = $foo->getProperty();
}
if (empty($foo->getAnotherProperty())) {
    $baz = $foo->setAnotherProperty(['baz'])->getAnotherProperty();
}