iostasis/getset

A trait that exposes selected class properties through getProperty() and setProperty() methods.

Installs: 12

Dependents: 0

Stars: 1

Watchers: 1

Language: PHP

0.3.0 2014-04-20 11:21 UTC

README

A trait that exposes selected class properties through getProperty() and setProperty() methods.

Installation

Via Composer:

{
    "require": {
        "iostasis/getset": "dev-master"
    }
}

Usage

Attach the \Iostasis\GetSet\GetSetTrait to your class:

use Iostasis\GetSet\GetSetTrait;

class User {
    use GetSetTrait;
}

This trait utilises the __call method. If your class already has a __call method defined, the process will be slightly more involved. Refer to the Using the base trait section below for further information.

Basic Usage

Once you have attached this trait to your class, you will then need to individually annotate each property:

class User {
    use GetSetTrait;

    /**
      * @GetSet\Read
      */
    protected $id;

    /**
      * @GetSet\Read
      * @GetSet\Write
      */
    protected $username;

    /**
      * @GetSet\Read
      * @GetSet\Write
      * @GetSet\Nullable
      */
    protected $email;

    protected $secret;
}

$user = new User;

The following calls will work:

  • $user->getID()
  • $user->getUsername()
  • $user->getPassword()
  • $user->setUsername('John')
  • $user->setEmail('john@example.org')
  • $user->setEmail(NULL)

The following calls will not work:

  • $user->getSecret(), because $secret has not been marked with the @GetSet\Read annotation.
  • $user->setID(1), because $id has not been marked with the @GetSet\Write annotation.
  • $user->setUsername(NULL), because $user has not been marked with the @GetSet\Nullable annotation.

All invalid calls will return an \InvalidArgumentException.

Shorthand

The trait also supports accessing readable properties via $user->username().

Using the base trait

If your class already has a __call() method, use the GetSetBaseTrait trait instead, and call its accessor method like so:

class MyClass {
    use GetSetBaseTrait;

    public function __call($method, $args) {
        /*
         * Some of our own processing here.
         * ...
         * None of our methods matched, so pass it on to the trait:
         */
        return $this->__call_GetSet($method, $args);
    }
}

Remarks

Precedence

If you have defined your own getX/setX methods in your class, they will take priority.

Testing

PHPUnit tests can be found in the tests directory.

Credits

License

This is licensed under the MIT License. Please refer to license.md.