parable-php / getset
Parable GetSet 帮助您轻松构建值集
1.0.0
2021-03-12 08:33 UTC
Requires
- php: >=8.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^8.0
- vimeo/psalm: ^4.6
README
Parable GetSet 允许通过值集合以整洁直观的方式处理全局变量,如 $_GET
和 $_SERVER
,同时还包括具有自身作用域的资源对象。
其主要优点是点符号(key.string
)用于嵌套值,例如 $getCollection->get('this.is.nested');
,这将查找 GetCollection
中存储的 ['this']['is']['nested']
。
集合默认返回请求的值或 null
,允许使用空合并进行可预测的使用。
安装
需要 Php 8.0+ 和 composer。
$ composer require parable-php/getset
用法
假设一个查询字符串如下: ?id=345&user[name]=username
$getCollection = new \Parable\GetSet\GetCollection(); echo $getCollection->get('id'); echo ':'; echo $getCollection->get('user.name');
将输出 345:username
显然,您也可以直接设置值
$getCollection->set('settings.mail.from', 'me@system'); // later $mail_from = $getCollection->get('settings.mail.from') ?? 'nobody';
集合
全局集合
它们对应于它们的 $_NAME
全局变量,也存在于超级全局变量 $GLOBALS
中。
CookieCollection
,处理$_COOKIE
数据。FilesCollection
,处理$_FILES
数据。GetCollection
,处理$_GET
数据。PostCollection
,处理$_POST
数据。ServerCollection
,处理$_SERVER
数据。SessionCollection
,处理$_SESSION
数据。
本地资源集合
DataCollection
,一个仅使用本地资源的通用集合,用于在应用程序中传递数据,例如配置。InputStreamCollection
,用于读取输入流。可以导入/解析json
或查询字符串数据。
您的自定义集合!
您可以通过扩展 BaseCollection
类并利用简单的点符号 get/set 逻辑来轻松构建自己的集合。
API
getAll(): array
- 返回当前存储的所有值getAllAndClear(): array
- 返回当前存储的所有值,然后清除它们get(string $key, $default = null): mixed
- 通过键返回值,如果未找到则返回$default
getAndRemove(string $key): mixed
- 通过键返回值并移除它,如果不存在则抛出异常set(string $key, $value): void
- 通过键设置值setMany(array $values): void
- 逐个设置传递的所有值,覆盖现有值setAll(array $values): void
- 设置所有值,覆盖任何现有值remove(string $key): void
- 通过键移除,如果已移除则抛出异常clear(): void
- 移除所有值has(string $key): bool
- 返回传递的键(或key.string
)当前是否存在count(): int
- 返回根值项目数量(不是所有嵌套值)
贡献
欢迎任何建议、错误报告或一般反馈。请使用 github issues 和 pull requests,或在 devvoh.com 找到我。
许可证
所有 Parable 组件都是开源软件,许可协议为 MIT 协议。