Giter Site home page Giter Site logo

data-transfer-object's Introduction

Data transfer object for arrays

Zero-dependency library to convert associative arrays to an object model

Installation

You can install the package via composer:

composer require amorphine/data-transfer-object

Purpose

The goal of this package is to give a convenient declared way to manipulate data extracted from associative arrays. Advantages of object structure:

  • Type safety (as long as PHP makes it possible)
  • Statically analyze and auto completion.
  • Scalar type casting

Let's look at the example of a JSON API call:

$post = $api->get('posts', 1); 

[
    'title' => '…',
    'body' => '…',
    'author' => '["id" => 1, ...]',
]

Working with this array is difficult, as we'll always have to refer to the documentation to know what's exactly in it. This package allows you to create data transfer object definitions, classes, which will represent the data in a structured way.

We did our best to keep the syntax and overhead as little as possible:

class PostData extends DataTransferObject
{
    /** @var string */
    public $title;
    
    /** @var string */
    public $body;
    
    /** @var AnotherDataTransferObjectImplementation */
    public $author;
}

An object of PostData can from now on be constructed like so:

$postData = new PostData([
    'title' => '…',
    'body' => '…',
    'author' => '…',
]);

Now you can use this data in a structured way:

$postData->title;
$postData->body;
$postData->author;

By adding doc blocks to our properties, their values will be validated against the given type; and a TypeError will be thrown if the value doesn't comply with the given type.

Here are the possible ways of declaring types:

use SomeNameSpace\Author;

class PostData extends DataTransferObject
{
    /**
     * Built in types: 
     *
     * @var string 
     */
    public $property;

    /**
     * You can override property data source (array key)
     *
     * @source keyWithSomeAnotherName
     */
    public $property;
    
    /**
     * Classes with their FQCN: 
     *
     * @var Author
     */
    public $property;
    
    /**
     * Lists of types: 
     *
     * @var Author[]
     */
    public $property;
    
    /**
     * Iterator of types: 
     *
     * @var iterator<Author>
     */
    public $property;
    
    /**
     * Union types: 
     *
     * @var string|int
     */
    public $property;
    
    /**
     * Nullable types: 
     *
     * @var string|null
     */
    public $property;
    
    /**
     * Mixed types: 
     *
     * @var mixed|null
     */
    public $property;
    
    /**
     * Any iterator : 
     *
     * @var iterator
     */
    public $property;
    
    /**
     * No type, which allows everything
     */
    public $property;
    
    /** 
     * PHP types declaration supported
     */
    public ?int $property;

}

PHP 7.4 typed properties are the source of types like PHP doc is. The compatibility of declared types is upon to the developer. Feel free to use one of them, both or none at all.

Source override

By default, the array key the value is taken from is the property name. If you need to specify the key of the original array the value should be taken from you should use @source doc comment:

class PostData extends DataTransferObject
{
    /** 
     * @var AuthorData
     * @source authorData
     */
    public $author;
}

Automatic casting of nested DTOs

If you've got nested DTO fields, data passed to the parent DTO will automatically be cast.

class PostData extends DataTransferObject
{
    /** @var AuthorData */
    public $author;
}

PostData can now be constructed like so:

$postData = new PostData([
    'author' => [
        'name' => 'Foo',
    ],
]);

Automatic casting of nested array DTOs

Similarly to above, nested array DTOs will automatically be cast.

class TagData extends DataTransferObject
{
    /** @var string */
   public $name;
}

class PostData extends DataTransferObject
{
    /** @var TagData[] */
   public $tags;
}

PostData will automatically construct tags like such:

$postData = new PostData([
    'tags' => [
        ['name' => 'foo'],
        ['name' => 'bar']
    ]
]);

Exception handling

Beside property type validation, you can also be certain that the data transfer object in its whole is always valid. On constructing a data transfer object, we'll validate whether all required (non-nullable) properties are set. If not, a Amorphine\DataTransferObject\Exceptions\DataTransferObjectError will be thrown.

Likewise, if you're trying to set non-defined properties, you'll get a DataTransferObjectError.

Testing

composer test

Limitations

  • Opcache: types and data sources are resolved through PHP comments so ensure opcache.save_comments equals 1

License

The MIT License (MIT). Please see License File for more information.

Powered by

See also

data-transfer-object's People

Contributors

amorphine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.