PHP code example of zendrop / data

1. Go to this page and download the library: Download zendrop/data 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/ */

    

zendrop / data example snippets




use Zendrop\Data\DataInterface;
use Zendrop\Data\DataTrait;
use Zendrop\Data\Attributes\ArrayOf;
use Zendrop\Data\Skippable;
use Zendrop\Data\ToArrayInterface;
use Zendrop\Data\ToArrayTrait;

class Tag implements DataInterface, ToArrayInterface
{
    use DataTrait;
    use ToArrayTrait;

    public function __construct(
        public readonly string $name
    ) {
    }
}

enum Occupation: string
{
    case Manager: 'manager';
    case Developer: 'developer';
}

class User implements DataInterface, ToArrayInterface
{
    use DataTrait;
    use ToArrayTrait;

    public function __construct(
        public readonly int $id,
        
        public readonly string $userName,
        
        /** @var Tag[] */
        #[ArrayOf(Tag::class)]
        public readonly array $tags,
        
        public readonly Occupation $occupation,
        
        public readonly string|Skippable $bio = Skippable::Skipped
    ) {
    }
}

// Create a User object from an array
$user = User::from([
    'id' => '42',                // will be converted to int
    'user_name' => 'John Doe',
    'tags' => [
        ['name' => 'friend'],    // will be converted to Tag class
        ['name' => 'zendrop']
    ],
    'occupation' => 'developer'  // will be converted to Occupation enum
    // 'bio' is optional and skipped here
]);

// Serialize the User object to an array
$arraySnakeCase = $user->toArray(); // Default snake_case
$arrayCamelCase = $user->toArray(ToArrayCase::Camel);
$arrayKebabCase = $user->toArray(ToArrayCase::Kebab);