1. Go to this page and download the library: Download haskel/map-serializer 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/ */
haskel / map-serializer example snippets
/** Define a class that you want to serialize */
class User
{
private $id;
private $name;
private status = 0;
private $role;
private $phone;
private $mail;
private group;
public function __construct($id, $name, $role)
{
$this->id = $id;
$this->name = $name;
$this->role = $role;
}
/**
* ... Boring code with getters and setters ...
*/
}
/** Specify the schema */
$schema = [
'id' => 'int',
'name' => 'string',
'status' => 'int',
'role' => 'string',
];
/** Add this schema definition, uniq schema name and class name to serializer */
$serializer->addSchema(User::class, 'default', $schema);
/** serialize some instance of the class */
$result = $serializer->serialize(new User('Alice', 'user'));
interface Formatter
{
public function format($value, $schemaName);
}
class DatetimeFormatter implements Formatter
{
public function format($value, $schemaName)
{
if (!$value instanceof DateTime) {
throw new FormatterException(sprintf('wrong value type'));
}
switch ($schemaName) {
case 'default':
case 'datetime':
default:
return $value->format("Y-m-d H:i:s");
case 'date':
return $value->format('Y-m-d');
case 'time':
return $value->format('H:i:s');
}
}
}
use Haskel\MapSerializer\Formatter\DatetimeFormatter;
use Haskel\MapSerializer\Serializer;
$serializer = new Serializer();
$serializer->addFormatter(new DatetimeFormatter());
$datetime = new DateTime('2015-10-21 12:00:00');
$serializer->format($datetime, 'date');
final class AppEntityUserExtractor extends \Haskel\MapSerializer\EntityExtractor\BaseExtractor
{
/** @var \App\Entity\User */
protected $entity;
protected function extract()
{
return [
"id" => $this->entity->getId(),
"name" => $this->entity->getName(),
];
}
public function exists($fieldName)
{
if (count($this->fields) === 0) {
$this->fields = $this->extract();
}
return array_key_exists($fieldName, $this->fields);
}
/**
* @param $fieldName
*
* @return mixed
*/
public function get($fieldName)
{
if (count($this->fields) === 0) {
$this->fields = $this->extract();
}
return $this->fields[$fieldName];
}
}
namespace Haskel\MapSerializer\EntityExtractor;
interface Extractor
{
public function get($fieldName);
public function exists($fieldName);
}
class UserExtractor implements Extractor
{
public function get($fieldName)
{
return 42;
}
public function exists($fieldName)
{
return true;
}
}