1. Go to this page and download the library: Download astral/php-serialize library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
astral / php-serialize example snippets
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
// ]
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";
}
$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
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');
}
}
}
use Astral\Serialize\Serialize;
class UserAddRequest extends Serialize {
public string $name;
public int $id;
}
class UserDetailRequest extends Serialize {
public int $id;
}
use Astral\Serialize\Serialize;
class UserDto extends Serialize {
public string $name,
public int $id;
}
use Astral\Serialize\Serialize;
use Astral\Serialize\OpenApi\Enum\MethodEnum;
#[\Astral\Serialize\OpenApi\Annotations\Tag('User Module Management')]
class UserController {
#[\Astral\Serialize\OpenApi\Annotations\Summary('Create User')]
#[\Astral\Serialize\OpenApi\Annotations\Route('/user/create')]
#[\Astral\Serialize\OpenApi\Annotations\RequestBody(UserAddRequest::class)]
#[\Astral\Serialize\OpenApi\Annotations\Response(UserDto::class)]
public function create()
{
return new UserDto();
}
#[\Astral\Serialize\OpenApi\Annotations\Summary('User Detail')]
#[\Astral\Serialize\OpenApi\Annotations\Route(route:'/user/detail', method: MethodEnum::GET)]
public function detail(UserDetailRequest $request): UserDto
{
return new UserDto();
}
}
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.