PHP code example of om / from-array

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

    

om / from-array example snippets


class Example {
  use FromArray;
  public string $a;
  public string $b;
  public string $c;
}

$example = Example::fromArray(
  [
    'a' => 'value of A',
    'b' => 'value of B',
    'c' => 'value of C',
  ],
);

echo json_encode($example, JSON_PRETTY_PRINT);

class Example
{
    use FromArray;
    
    #[Property(from: '_id')]
    public int $id;
}

$example = Example::fromArray(['_id' => 123]);
assert($example->id === 123);

function addPrefix(mixed $value) {
    return 'PREFIX_' . $value;
}

class Example
{
    use FromArray;
    
    #[Property(loader: 'addPrefix')]
    public string $name;
}

$example = Example::fromArray(['name' => 'name']);
assert($example->name === 'PREFIX_name');


use DataLoader\Loader;use DataLoader\Property;

class MyLoader {
    public function __invoke($value, Property $property){
        return match ($property->name) {
            'id' => (int) $value,
            'names' => explode(',', $value),
            default => $value,
        }
    }
} 

#[Loader(MyLoader::class)]
class Example
{
    use FromArray;
    public mixed $id = null;
    public array $names = [];
    public string $other = '';
    
}

$example = Example::fromArray([
    'id' => '123',
    'names' => 'John,Doe,Smith'
    'other' => 'value',
]);

class Example
{
    use FromArray;
    
    #[Type(name: Types::Int, allowNull: true, class: null)]
    public mixed $id;
}

class ExampleObject {
    public function __construct(public string $name = null) {}
}

class Example
{
    use FromArray;
    
    #[Type(name: Types::ArrayOfObjects, class: ExampleObject::class)]
    public array $objects = [];
}

$example = Example::fromArray([
    'objects' => [
        ['name' => 'John'],
        ['name' => 'Doe'],
    ],
]);

// prepare metadata
$metadata = new Metadata();
$metadata->resolve(Example::class, MyObject::class);
$data = $metadata->getArrayCopy();

// restore singleton data
Metadata::fromCache($data);