easyswoole / spl
php stander lib
Requires
- php: >=8.1.0
- ext-dom: *
- ext-json: *
- ext-simplexml: *
Requires (Dev)
- easyswoole/swoole-ide-helper: ^1.0
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- 2.x-dev
- 2.2.4
- 2.2.3
- 2.2.2
- 2.2.1
- 2.1.7
- 2.1.6
- 2.1.5
- 2.1.4
- 2.1.3
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.9
- 2.0.8
- 2.0.7
- 2.0.6
- 2.0.5
- 2.0.4
- 2.0.3
- 2.0.2
- 2.0.1
- 1.4.1
- 1.4.0
- 1.3.10
- 1.3.9
- 1.3.8
- 1.3.7
- 1.3.6
- 1.3.5
- 1.3.4
- 1.3.3
- 1.3.2
- 1.3.1
- 1.3.0
- 1.2.4
- 1.2.3
- 1.2.2
- 1.2.1
- 1.2.0
- 1.1.15
- 1.1.14
- 1.1.13
- 1.1.12
- 1.1.11
- 1.1.10
- 1.1.9
- 1.1.8
- 1.1.7
- 1.1.6
- 1.1.5
- 1.1.4
- 1.1.3
- 1.1.2
- 1.1.1
- 1.1.0
- 1.0.9
- 1.0.8
- 1.0.7
- 1.0.6
- 1.0.5
- 1.0.4
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- dev-master
This package is auto-updated.
Last update: 2026-11-28 14:16:55 UTC
README
PHP 常用标准数据结构与工具库,提供以下组件:
SplBean(含#[ConvertBean]、#[ConvertBeanList]、ConvertBeanInterface):对象数据映射、嵌套转换与序列化SplArray:增强型数组对象(点语法嵌套读写、通配符提取、过滤、排序、XML 导出)SplString:面向对象的链式字符串处理工具SplStream:内存与资源流封装SplFileStream:支持文件锁的文件流封装SplDoubleLink:轻量双向链表节点基类
环境要求
- PHP >= 8.1
- 扩展:
ext-json、ext-dom、ext-simplexml
安装
composer require easyswoole/spl
1. SplBean
SplBean 用于将数组数据映射到对象属性,并提供序列化、过滤与嵌套对象转换能力。
- 仅处理声明的
public/protected非静态属性;自动忽略private属性与输入数组中的未知键。 - 构造顺序固定为:初始化属性与转换配置 → 执行
restore($data)→ 执行initialize()。 - 仅对显式标注
#[ConvertBean]或#[ConvertBeanList]的属性执行嵌套转换,不对未标注属性做隐式还原。
1.1 基础用法
use EasySwoole\Spl\SplBean; class UserBean extends SplBean { public int $id = 0; public string $name = ''; public ?string $nickname = null; protected string $role = 'guest'; protected function initialize(): void { if ($this->nickname === null) { $this->nickname = $this->name; } } } $user = new UserBean([ 'id' => 1, 'name' => 'Alice', 'unknown' => 'ignored', ]); $user->toArray(); // ['id' => 1, 'name' => 'Alice', 'nickname' => 'Alice', 'role' => 'guest'] $user->getProperty('role'); // 'guest'(读取未初始化强类型属性安全返回 null) $user->allProperty(); // ['id', 'name', 'nickname', 'role'] (string)$user; // JSON 字符串(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) // 局部更新属性 $user->restore(['name' => 'Bob']);
1.2 序列化与过滤
SplBean 实现 \JsonSerializable,toArray() 会递归序列化嵌套的 SplBean、ConvertBeanInterface 实例及其数组。支持以下过滤模式:
$bean->toArray(); // 全部属性 $bean->toArray(SplBean::FILTER_NOT_NULL); // 过滤 null $bean->toArray(SplBean::FILTER_NOT_EMPTY); // 过滤 empty 值 $bean->toArray(SplBean::FILTER_NULL); // 仅保留 null $bean->toArray(SplBean::FILTER_EMPTY); // 仅保留 empty 值 $bean->toArray(fn ($val) => $val !== ''); // 自定义回调过滤
1.3 构造器属性提升(Promoted Properties)
构造器提升属性若已由 PHP 初始化,会保留其构造赋值,避免 nullable 参数被重置为 null,也避免重复初始化 readonly 属性;若显式传入 $data,仍按 restore() 与 PHP readonly 规则执行。
class Member extends SplBean { public function __construct(public readonly int $id, public ?string $name = null, ?array $data = null) { parent::__construct($data); } } $member = new Member(7, 'Alice'); $member->toArray(); // ['id' => 7, 'name' => 'Alice']
1.4 单个嵌套对象:#[ConvertBean] 与 ConvertBeanInterface
通过 #[ConvertBean(className, createObjectWhenNull)] 为单个子属性声明自动转换。目标类必须是具体的 SplBean 子类或 ConvertBeanInterface 实现类。
- 输入支持:数组、JSON 字符串,或已是目标类的对象实例(直接复用)。
- 空值与缺失规则:
- 可空属性(如
?AddressBean):key 缺失或显式传null时赋值为null。 - 非空属性(如
AddressBean):createObjectWhenNull: false(默认):key 缺失或显式传null时抛出\InvalidArgumentException。createObjectWhenNull: true:key 缺失或显式传null(构造与restore()均适用)时自动创建默认对象(new $class()或$class::toObject(null))。
- 可空属性(如
use EasySwoole\Spl\AbstractInterface\ConvertBeanInterface; use EasySwoole\Spl\Attribute\ConvertBean; use EasySwoole\Spl\SplBean; class AddressBean extends SplBean { public string $city = ''; } class Money implements ConvertBeanInterface { public function __construct(public int $cents) {} public static function toObject(mixed $data): object { return new self((int)$data); } public function toValue(): int { return $this->cents; } } class OrderBean extends SplBean { #[ConvertBean(AddressBean::class, createObjectWhenNull: true)] public AddressBean $shippingAddress; #[ConvertBean(AddressBean::class)] public ?AddressBean $billingAddress = null; #[ConvertBean(Money::class)] public ?Money $amount = null; } $order = new OrderBean([ 'shippingAddress' => ['city' => 'Xiamen'], 'amount' => 19900, ]); $order->shippingAddress->city; // 'Xiamen' $order->billingAddress; // null $order->amount->cents; // 19900 $order->toArray(); // ['shippingAddress' => ['city' => 'Xiamen'], 'billingAddress' => null, 'amount' => 19900]
1.5 对象列表:#[ConvertBeanList]
#[ConvertBeanList(className, createEmptyListWhenNull)] 继承自 ConvertBean,同样支持 SplBean 子类与 ConvertBeanInterface 实现类,可将数组或 JSON 数组字符串中的元素逐项转换,并保留数组键名。
createEmptyListWhenNull默认为true:- 非空
array属性在 key 缺失或显式传null时自动初始化为[];设为false时抛出\InvalidArgumentException。 - 可空
?array属性在 key 缺失或显式传null时保持null。
- 非空
use EasySwoole\Spl\Attribute\ConvertBeanList; use EasySwoole\Spl\SplBean; class ItemBean extends SplBean { public int $id = 0; public string $name = ''; } class CartBean extends SplBean { /** @var list<ItemBean> */ #[ConvertBeanList(ItemBean::class)] public array $items; /** @var list<Money> */ #[ConvertBeanList(Money::class)] public array $amounts; /** @var list<ItemBean>|null */ #[ConvertBeanList(ItemBean::class)] public ?array $coupons = null; } $cart = new CartBean([ 'items' => [ ['id' => 1, 'name' => 'Apple'], '{"id":2,"name":"Banana"}', new ItemBean(['id' => 3, 'name' => 'Orange']), ], 'amounts' => [100, 250], ]); $cart->toArray();
1.6 反射缓存机制
SplBean 按实际运行时类缓存 ReflectionProperty、ReflectionAttribute 及静态类型元数据,减少大量同类型 Bean 构造与序列化时的重复反射开销。缓存仅共享类级元数据,继承类之间独立缓存;每个 Bean 实例仍独立构造转换注解实例与默认业务对象,并支持注解构造过程中的重入。
2. SplArray
SplArray 继承自 \ArrayObject,支持对象属性访问、点语法嵌套读写、集合操作与 XML 导出。
use EasySwoole\Spl\SplArray; $arr = new SplArray([ 'user' => ['name' => 'Alice', 'age' => 25], 'items' => [ ['id' => 1, 'title' => 'Book'], ['id' => 2, 'title' => 'Pen'], ], ]); // 点语法与通配符读写 $arr->get('user.name'); // 'Alice' $arr->get('user.missing', 'default'); // 'default' $arr->get('items.*.id'); // [1, 2] $arr->set('user.city', 'Xiamen'); $arr->unset('user.age'); // 或 $arr->delete('user.age') $arr->keys('user'); // ['name', 'city'] // 属性风格访问与 JSON 输出 $arr->extra = 'ok'; (string)$arr; // JSON 字符串 // 常用集合操作(多数返回新的 SplArray 实例,支持链式调用) $nums = new SplArray([3, 1, 2, 2, 3]); $nums->unique()->sort()->values()->getArrayCopy(); // [1, 2, 3] $nums->multiple()->getArrayCopy(); // [3 => 2, 4 => 3](重复项) $rows = new SplArray([ ['id' => 10, 'name' => 'A'], ['id' => 20, 'name' => 'B'], ]); $rows->column('name', 'id')->getArrayCopy(); // [10 => 'A', 20 => 'B'] $data = new SplArray(['a' => 1, 'b' => 2, 'c' => 3]); $data->filter('a,b')->getArrayCopy(); // ['a' => 1, 'b' => 2](仅保留) $data->filter(['c'], true)->getArrayCopy(); // ['a' => 1, 'b' => 2](排除) $data->flip()->getArrayCopy(); // [1 => 'a', 2 => 'b', 3 => 'c'] // 原地修改:合并、重载与清空 $data->merge(['d' => 4]); $data->loadArray(['x' => 1]); $data->flush(); // 导出 XML(支持 CDATA、自定义根节点与数字索引节点名) $xml = (new SplArray([ 'title' => 'Demo', 'items' => [['id' => 1], ['id' => 2]], ]))->toXML(CD_DATA: false, rootName: 'xml', subArrayItemKey: 'item');
3. SplString
SplString 继承自 SplStream,提供面向对象的链式字符串操作(修改类方法原地更新内容并返回 $this)。
use EasySwoole\Spl\SplString; $str = new SplString(' hello_easyswoole_spl '); // 基础链式操作 $str->trim()->studly(); // 'HelloEasyswooleSpl' $str->camel(); // 'helloEasyswooleSpl' $str->snake(); // 'hello_easyswoole_spl' $str->kebab(); // 'hello-easyswoole-spl' $str->upper(); // 'HELLO-EASYSWOOLE-SPL' $str->lower(); // 'hello-easyswoole-spl' $str->length(); // 20 // 截取、替换与分割 (new SplString('a,b,c'))->explode(',')->getArrayCopy(); // ['a', 'b', 'c'] (new SplString('abcdef'))->split(2)->getArrayCopy(); // ['ab', 'cd', 'ef'] (new SplString('[hello]'))->between('[', ']'); // 'hello' (new SplString('user@example.com'))->before('@'); // 'user' (new SplString('user@example.com'))->after('@'); // 'example.com' (new SplString('a-b-a'))->replaceFirst('a', 'x'); // 'x-b-a' (new SplString('a-b-a'))->replaceLast('a', 'x'); // 'a-b-x' (new SplString('? + ? = ?'))->replaceArray('?', ['1', '2', '3']); // '1 + 2 = 3' (new SplString('foo/bar'))->start('/'); // '/foo/bar' (new SplString('<b>hi</b>'))->stripTags(); // 'hi' (new SplString('hi'))->pad(5, '0', STR_PAD_LEFT); // '000hi' (new SplString('ab'))->repeat(3); // 'ababab' // 匹配与判断 $s = new SplString('EasySwoole 2026'); $s->exist('swoole', ignoreCase: true); // true $s->startsWith('Easy'); // true $s->endsWith(['2025', '2026']); // true $s->compare('easyswoole 2026', 1); // 0(忽略大小写相等) $s->regex('/\d+/'); // '2026'($rawReturn = true 返回完整匹配数组) // 编码与 Unicode 转换 $cn = new SplString('中文'); $cn->toUnicode(); // '\U4E2D\U6587' $cn->unicodeToUtf8(); // '中文' $cn->utf8(); // 自动检测并转为 UTF-8(底层调用 encodingConvert)
4. SplStream
SplStream 是对 PHP 流资源(默认 php://memory)的面向对象封装,提供与 PSR-7 Stream 风格一致的读写与指针控制接口;对象销毁时自动关闭流。
use EasySwoole\Spl\SplStream; // 从字符串、实现了 __toString 的对象或已有 resource 构造 $stream = new SplStream('hello'); $stream->seek(0, SEEK_END); $stream->write(' world'); $stream->getSize(); // 11 $stream->tell(); // 11 $stream->eof(); // false $stream->rewind(); // 指针回到开头 $stream->read(5); // 'hello' $stream->getContents(); // ' world'(从当前位置读到末尾) (string)$stream; // 'hello world'(始终从开头读取全部内容) // 状态与元数据 $stream->isReadable(); $stream->isWritable(); $stream->isSeekable(); $stream->getMetadata('mode'); $stream->getStreamResource(); // 截断、分离与关闭 $stream->truncate(5); // 截断为 5 字节 $res = $stream->detach(); // 分离底层 resource,由调用方自行管理 $stream->close();
5. SplFileStream
SplFileStream 继承自 SplStream,用于直接打开本地文件流(默认模式 'c+'),并额外提供基于 flock 的文件锁方法 lock() / unlock()。
use EasySwoole\Spl\SplFileStream; $file = new SplFileStream('/tmp/demo.txt', 'c+'); if ($file->lock(LOCK_EX)) { try { $file->truncate(0); $file->rewind(); $file->write("line 1\nline 2\n"); $file->rewind(); $content = $file->getContents(); } finally { $file->unlock(); } } $file->close();
6. SplDoubleLink
SplDoubleLink 是轻量的双向链表节点基类,支持按需懒创建前后节点(通过反射实例化 static::class)及解除链接。
use EasySwoole\Spl\SplDoubleLink; class StepNode extends SplDoubleLink { public function __construct(public string $name = '') {} } $first = new StepNode('init'); $second = $first->next('validate'); // 首次调用自动创建并返回 StepNode('validate') $third = $second->next('finish'); $first->hasNext(); // true $first->next()->name; // 'validate' $second->hasPre(); // false(next() 仅设置当前节点的 next 指针) $prev = $second->pre('before'); // 创建并返回前驱节点 StepNode('before') $second->hasPre(); // true $second->delPre(); // 解除前驱引用 $first->delNext(); // 解除后继引用
运行测试
composer test
License
Apache-2.0