tuupola / witchcraft
Opionated magic methods as traits
Fund package maintenance!
tuupola
Installs: 15 193
Dependents: 2
Suggesters: 0
Security: 0
Stars: 23
Watchers: 4
Forks: 2
Open Issues: 1
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: ~4.3
- squizlabs/php_codesniffer: ~1.5
This package is auto-updated.
Last update: 2022-04-12 06:48:36 UTC
README
Opionated PHP magic methods as traits.
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.