tuupola / witchcraft
此包已废弃,不再维护。未建议替代包。
以特性形式实现的偏执魔法方法
1.1.0
2016-10-08 19:27 UTC
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
将偏执的PHP魔法方法作为特性。
安装
您可以使用composer安装最新版本。
$ composer require tuupola/witchcraft
使用
您有您常用的类,包含样板式的访问器和修改器。
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"); } }
所有这些都与ide自动补全等一切配合得很好。问题是您的代码看起来相当丑陋。
$unicorn = new Unicorn(); $unicorn->setBirthday("1930-24-12")->setColor("rainbow"); print $unicorn->getAge();
魔法方法
Witchcraft来拯救。如果您添加Witchcraft\MagicMethods
特性,您可以使用漂亮的方法。
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();
魔法属性
如果您添加Witchcraft\MagicProperties
特性,您可以使用漂亮的属性。
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;
动态方法
作为额外的好处,您可以动态地将方法分配给对象。
$unicorn->something(function ($input) { return "Got {$input}!"; }); $unicorn->something("milk"); /* Got milk! */
$unicorn->something = function ($input) { return "No {$input} :("; }; $unicorn->something("beer"); /* No beer :() */
为什么?
因为我认为getFoo()
和setFoo("bar")
很丑陋。
测试
您可以手动运行测试...
$ composer test
...或者每次代码更改时自动运行。您需要entr来实现这一点。
$ brew install entr $ composer watch
贡献
有关详细信息,请参阅CONTRIBUTING。
安全
如果您发现任何与安全相关的问题,请通过电子邮件tuupola@appelsiini.net联系,而不是使用问题跟踪器。
许可
MIT许可证(MIT)。有关更多信息,请参阅许可文件。