blabs-dev / php-dictionary
一个简单的抽象类,允许您使用常量快速编写字典
v2.0.0
2021-09-29 18:00 UTC
Requires
- php: ^7.3|^8.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-29 05:50:02 UTC
README
一个简单但强大的包,用于使用php管理原始值快速“字典”。
"字典"的概念指的是特定领域的有效值的简单列表。该包允许您使用php常量定义字典,并快速访问其值,而不在类上下文中。
它并非旨在实现一个 可枚举类,它只是让您能够快速获取您类中所有常量的值作为数组,或者检查一个值是否在字典中,从而可以被认为是“有效”的。
安装
composer require blabs-dev/dictionary
用法
该包允许您选择是否希望在类中扩展一个抽象类或使用特性来实现字典功能。
第一种方法对于单职责类(如简单的字符串字典类)很有用,而后者如果您希望类已经具有与其他依赖项的继承关系,并且只想能够检查值的有效性,则可能更方便。
使用继承的示例用法
这里有一个扩展字典抽象类的字典示例。
// create a class extending the Dictionary abstract use Blabs\Dictionary\Dictionary; class Fruits extends Dictionary { const APPLE = 'apple'; const BANANA = 'banana'; const ORANGE = 'orange'; } // return all "values" from the dictionary Fruits::values() // outputs [ 'apple', 'banana', 'orange' ] // check if a value is valid Fruits::isValid('apple') // outputs `true` Fruits::isValid('tomato') // outputs `false`
使用组合的示例用法
这里有一个假设的蔬菜仓库示例,它已经扩展了另一个名为 StockService
的类来检查产品的可用性。在这种情况下,您可以包含 WithDictionary
特性来添加字典功能。
use Blabs\Dictionary\WithDictionary; class MyVegetablesWarehouse extends StockService { use WithDictionary; // include the trait in your class to use dictionary features // Defines all products handled by the warehouse const AUBERGINE = 'aubergine'; const SWEET_PEPPER = 'sweet pepper'; const TOMATO = 'tomato'; // Checks if a product is a "legit" vegetable :) public function isVegetable($product) { // recalls dictionary trait method to check if the dictionary has specified product return self::isValid($product); } // Lists all available vegetables public function getVegetables() { // recalls dictionary static method to list all vegetable products return self::values(); } // Get stocks for a specific vegetable public function getVegetablesStocks($vegetable) { // uses dictionary static method to check if the product is "valid" before doing anything else if (! self::isValid($vegetable)) throw new InvalidArgumentException('this is not a veggie!') // then recalls a hypothetical method from elsewhere (i.e. the StockService class) return $this->getStocks($vegetable); } // Creates an "inventory" array public function getVegetablesInventory() { $stocks = []; foreach (self::values() as $vegetable) // cycle all vegetables in the dictionary { $stocks[$vegetable] = $this->getStocks($vegetable); } return $stocks; } } // the class will still expose static methods outside its context MyVegetablesWarehouse::values() // outputs [ 'aubergine', 'sweet pepper', 'tomato' ] // check if a value is valid MyVegetablesWarehouse::isValid('apple') // outputs `false` MyVegetablesWarehouse::isValid('tomato') // outputs `true`
待办事项
- 过滤
- 排序
- 映射
免责声明
请注意 当php 8.1发布时,这个类可能会变得没有用处,因为新的 enums
API 将包含枚举的实现。如果您需要一个可枚举类的完整实现,您可以使用更稳健且受支持的包,例如 myclabs/php-enum。