rumd3x / php-countable
提供多个面向对象计数器和计数工具的库
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^7
This package is auto-updated.
Last update: 2024-09-29 05:28:46 UTC
README
提供多个面向对象计数工具的库。
安装
composer require rumd3x/php-countable
用法示例
- 作为 while 循环的退出条件
use use Rumd3x\Countable\Counters\BasicCounter; $counter = new BasicCounter(10); while (!$counter->isZero()) { // Do stuff... $counter->decrement(); }
- 作为迭代器计数器
use use Rumd3x\Countable\Counters\BasicCounter; $counter = new BasicCounter(); foreach($myArrayOfStuff as $value) { // Do stuff... $counter->incrementBy($value->quantity); } echo "Found {$counter->getCounter()} stuff";
API 描述
本库提供
- 2 个计数器接口
Decrementable
和Incrementable
。 - 一个基本的
AbstractCounter
,可以在此基础上扩展。 - 4 个计数器实现,它们都实现了这两个接口,并且使用
AbstractCounter
作为基础。
Incrementable
和 Decrementable
接口提供了以下方法
/** Incrementable **/ public function increment(): int; // Increment the counter by one and returns the previous value public function incrementBy(int $incrementQuantity): int; //Increments the counter by incrementQuantity and returns the previous value /** Decrementable **/ public function decrement(): int; // Decrements the counter by one and returns the previous value public function decrementBy(int $decrementQuantity): int; // Decrements the counter by decrementQuantity and returns the previous value
每个计数器实现以不同的方式处理计数器的增加和减少
BasicCounter
Rumd3x\Countable\Counters\BasicCounter
它是 Incrementable 和 Decrementable 接口的最基本实现,它不对输入进行任何转换,也不会抛出任何异常。
StandardCounter
Rumd3x\Countable\Counters\StandardCounter
StandardCounter 保持一个计数器,并可以通过实现 Incrementable 和 Decrementable 接口来增加或减少其值。它也可以对负数进行计数。
SmartCounter
Rumd3x\Countable\Counters\SmartCounter
SmartCounter 与 StandardCounter 相同,但在尝试通过负数增加或减少时不会抛出 Rumd3x\Countable\Exceptions\NegativeQuantityException
,而是迅速将值转换为正数。
AbsoluteCounter
Rumd3x\Countable\Counters\AbsoluteCounter
AbsoluteCounter 与 StandardCounter 类似,但如果程序尝试减到 0 以下,则会抛出 Rumd3x\Countable\Exceptions\NegativeCounterExpcetion
。它确保计数器始终为正。
AbstractCounter
AbstractCounter
实现以下方法:(这使得它也适用于库提供的所有 4 个计数器实现)
/** * Retrieve the current counter value * @return integer */ public function getCounter(): int; /** * Returns true if the counter is zero, false otherwise * @return boolean */ public function isZero(): bool; /** * Returns true if the counter is less than zero, false otherwise * @return boolean */ public function isNegative(): bool; /** * Returns true if the counter is greater than zero, false otherwise * @return boolean */ public function isPositive(): bool;