youcanshop / cereal
简化序列化管理的一个包。
v1.1.2
2023-09-21 15:04 UTC
Requires
- php: >=7.4
Requires (Dev)
- laravel/framework: >=7
- pestphp/pest: ^1
- phpstan/phpstan: ^1.10
- rector/rector: ^0.18.3
README
Cereal 是一个PHP包,允许您轻松地对数据进行序列化和反序列化。
安装
您可以通过composer安装此包
composer require youcanshop/cereal
使用方法
要开始使用此包,您需要创建一个实现了 YouCanShop\Cereal\Contracts\Serializable
接口的类,并使用包含一些默认配置辅助器的 YouCanShop\Cereal\Cereal
特性。
class User implements Serializable { use Cereal; public int $age; public string $name; public float $weight; public bool $isStraight; public function __construct( string $name, int $age, float $weight, bool $isStraight ) { $this->age = $age; $this->name = $name; $this->weight = $weight; $this->isStraight = $isStraight; } public function serializes(): array { return ['name', 'age', 'weight', 'isStraight']; } }
serializes
方法返回您想要序列化的属性数组。然后,包将根据类型提示的属性自动序列化和反序列化数据。
注意
- 该包将仅序列化类型提示的公共属性。
- 该包将按照在
serialize
方法中定义的顺序序列化属性。
序列化处理器
在大多数用例中,您可能需要以不同的方式序列化和反序列化某些属性。例如,您可能希望将 DateTime
对象序列化为时间戳,或将 User
对象序列化为数组或其他内容。为此,您需要创建自己的序列化处理器并将其添加到 YouCanShop\Cereal\SerializationHandlerFactory
。
class UserHandler implements SerializationHandler { protected UserRepository $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } public function serialize(Serializable $serializable, $value): string { return $value->getId(); } /** * @param string $value * * @return ?User */ public function deserialize(Serializable $serializable, $value): ?User { return $this->userRepository->find($value); } }
在上面的示例中,当尝试序列化用户对象时,我们只序列化ID,并且在尝试反序列化时,我们从数据库中再次获取它。
然后,您需要将处理器添加到 YouCanShop\Cereal\SerializationHandlerFactory
use YouCan\Cereal\SerializationHandlerFactory; SerializationHandlerFactory::getInstance() ->addHandler(User::class, new UserHandler($userRepository));
现在,当处理将要被序列化的对象时,如果它包含一个 User
实例,它将自动使用我们的处理器进行序列化和反序列化。
class Post implements Serializable { use SerializeTrait; public string $title; public string $content; public User $author; public function __construct(string $title, string $content, User $author) { $this->title = $title; $this->content = $content; $this->author = $author; } public function serializes(): array { return ['title', 'content', 'author']; } }
Laravel 桥接
// TODO