PHP code example of youcanshop / cereal

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

    

youcanshop / cereal example snippets


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'];
    }
}

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);
    }
}

use YouCan\Cereal\SerializationHandlerFactory;

SerializationHandlerFactory::getInstance()
    ->addHandler(User::class, new UserHandler($userRepository));

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'];
    }
}