webhappens / conditional-methods
通过在调用时简单添加 If 或 Unless 来使方法调用条件化。
v0.3.0
2021-01-23 15:27 UTC
Requires
- php: ^7.3|^8.0
Requires (Dev)
- phpunit/phpunit: ^7.5.15|^8.4|^9.0
- symfony/var-dumper: ^4.3.4|^5.0
This package is auto-updated.
Last update: 2024-09-23 23:19:57 UTC
README
条件方法
通过在调用时简单添加 If 或 Unless 来使方法调用条件化。条件方法允许您传递一个条件来决定是否执行它们,从而无需将它们包裹在逻辑中。这在链式调用时特别有用。
安装
通过 composer 安装
composer require webhappens/conditional-methods
将 ConditionalMethods
特性插入到您的类中
use \WebHappens\ConditionalMethods\ConditionalMethods;
如果您的类已经使用 __call
方法,请向其中添加以下内容
public function __call($method, $arguments) { if ($type = static::matchConditionalMethod($method)) { return $this->callConditionalMethod($type, $method, $arguments); } // ... // throw new \BadMethodCallException(); }
If
将 If
添加到任何方法调用的末尾,并将条件作为第一个参数传递。
$insurer->renewIf($car->insuranceIsDue(), $car);
这取代了需要做类似以下操作的需求:
if ($car->insuranceIsDue()) { $insurer->renew($car); }
Unless
Unless
与 If
的工作方式相同,只是条件被反转。
将 Unless
添加到任何方法调用的末尾,并将条件作为第一个参数传递。
$insurer->renewUnless($car->insuranceIsValid(), $car);
致谢
- Sam Leicester: sam@webhappens.co.uk
- Ben Gurney: ben@webhappens.co.uk
- 特别感谢 Spatie 团队在这方面的启发,他们的 laravel-html 包 ❤️
- 所有贡献者
我们的 Str
类只是 Laravel 的 Str
辅助函数的一些功能的拷贝。
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。