astral / php-serialize
v1.0.3
2025-03-27 05:47 UTC
Requires
- php: ^8.1
- fakerphp/faker: ^1.23
- illuminate/support: ^6.0||^7.0||^8.0||^9.0||^10.0||^11.0||^12.0
- phpdocumentor/reflection: ^6.0
- phpdocumentor/reflection-docblock: ^5.5
- psr/simple-cache: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- mockery/mockery: ^1.6
- pestphp/pest: ^2.30
- phpbench/phpbench: ^1.2
- phpstan/phpstan: ^2.0.2
README
Languages
php-serialize
An advanced PHP serialization tool leveraging attributes for flexible object-to-array and JSON conversion. Supports property aliases, type conversions, and nested object handling. Ideal for APIs, data persistence, and configuration management.
Quick Start
Installation
Install using Composer:
composer require astral/php-serialize
Basic Usage
use Astral\Serialize\Serialize; class User extends Serialize { public string $name, public int $age } // Create object from array $user = User::from([ 'name' => 'John Doe', 'age' => 30 ]); // Access object properties echo $user->name; // Output: John Doe echo $user->age; // Output: 30 // Convert to array $userArray = $user->toArray(); // $userArray contents: // [ // 'name' => 'John Doe', // 'age' => 30 // ]
Other Features
- Immutability: Read-only properties cannot be modified after construction
use Astral\Serialize\Serialize; class User extends Serialize { public function __construct( public readonly string $name, public readonly int $age ) {} } $user = User::from([ 'name' => 'John Doe', 'age' => 30 ]); try { $user->name = 'Jane Doe'; // Compile-time error: cannot modify read-only property } catch (Error $e) { echo "Read-only properties cannot be reassigned"; }
- Type-Safe Initialization
$user = User::from([ 'name' => 123, // Integer will be converted to string 'age' => '35' // String will be converted to integer ]); echo $user->name; // Output: "123" echo $user->age; // Output: 35
- Constructor Initialization
use Astral\Serialize\Serialize; class User extends Serialize { public function __construct( public readonly string $name, public readonly int $age ) { // Can add additional validation or processing logic in the constructor if (strlen($name) < 2) { throw new \InvalidArgumentException('Name is too short'); } } }