tuupola/witchcraft

Opionated magic methods as traits

1.1.0 2016-10-08 19:27 UTC

README

Opionated PHP magic methods as traits.

Author Software License Build Status HHVM Status Coverage

Install

You can install latest version using composer.

$ composer require tuupola/witchcraft

Usage

You have your usual class with boilerplate accessors and mutators.

class Unicorn
{
    private $color;
    private $birthday;

    public function __construct($color = "white", $birthday = null)
    {
        $this->color = $color;
        $this->birthday = $birthday;
    }

    public function getColor()
    {
        return $this->color;
    }

    public function setColor($color)
    {
        $this->color = $color;
        return $this;
    }

    public function getBirthday()
    {
        return $this->birthday;
    }

    public function setBirthday($birthday)
    {
        $this->birthday = DateTime::createFromFormat("Y-m-d", $birthday);
        return $this;
    }

    public function getAge()
    {
        $now = new DateTime();
        return $this->birthday->diff($now)->format("%y years");
    }
}

It all works really nice with ide autocompletes and everything. Problem is your code looks quite ugly.

$unicorn = new Unicorn();
$unicorn->setBirthday("1930-24-12")->setColor("rainbow");
print $unicorn->getAge();

Magic methods

Witchcraft to the resque. If you add Witchcraft\MagicMethods trait you can use pretty methods.

class Unicorn
{
    use \Witchcraft\MagicMethods;

    /* Rest of the code stays exactly the same. */
}
$unicorn = new Unicorn();
$unicorn->birthday("1930-24-12")->color("rainbow");
print $unicorn->age();

Magic properties

If you add Witchcraft\MagicProperties trait you can use pretty properties.

class Unicorn
{
    use \Witchcraft\MagicProperties;

    /* Rest of the code stays exactly the same. */
}
$unicorn = new Unicorn();
$unicorn->birthday = "1930-24-12";
$unicorn->color = "rainbow";
print $unicorn->age;

Dynamic methods

As a bonus you can dynamically assing methods to the object.

$unicorn->something(function ($input) {
    return "Got {$input}!";
});

$unicorn->something("milk");

/* Got milk! */
$unicorn->something = function ($input) {
    return "No {$input} :(";
};

$unicorn->something("beer");

/* No beer :() */

Why?

Because I think getFoo() and setFoo("bar") are ugly.

Testing

You can run tests either manually...

$ composer test

... or automatically on every code change. You will need entr for this to work.

$ brew install entr
$ composer watch

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email tuupola@appelsiini.net instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.