Skip to content
A simple data transfer object
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
tests
.gitattributes
.gitignore
.travis.yml
CHANGELOG.md
LICENSE.md
README.md
composer.json
phpunit.xml

README.md

DataTransferObject

Latest Stable Version Build Status Coverage Status Quality Score License

This class is designed to make it easy to add and view data. Load objects, arrays, or json; read with object, array, or dot notation; output to json string.

Usage

You can instantiate the class with an array, arrayable object, or json string. These are all equivalent:

$object = new StdObject;
$object->foo = 'bar';

$dto = new DTO($object);
$dto = new DTO(['foo'=>'bar']);
$dto = new DTO('{"foo":"bar"}');

$dto = DTO::make($object);
$dto = DTO::make(['foo'=>'bar']);
$dto = DTO::make('{"foo":"bar"}');

Read data with array, object, or dot notation:

echo $dto['x'];
echo $dto->x;
echo $dto->get('x');

These will also handle nested sets:

echo $dto['x']['y']['z'];
echo $dto->x->y->z;
echo $dto->get('x.y.z');

By default, an empty string will be returned if a missing property is accessed. Other possibilities:

$dto = new DTO([], 'x');            // instantiate with a given default
$dto->setDefault('x');              // change the default
$dto->get('path.to.key', 'x');      // override default for this method call
$dto->setDefault(Null);             // throw an UndefinedProperty exception

Add new data with array or object notation:

$dto['x'] = 'y';
$dto->x = 'y';

Count and iterate the properties:

$dto = new DTO([...])
$count = count($dto);
foreach($dto as $key=>$value)
    // do something

Laravel Support

There are two versions of the data transfer object that implement Laravel-specific interfaces. Use one of these classes if you want Laravel to work with DTOs as first-class Laravel objects.

  • Laravel4DTO implements JsonableInterface and ArrayableInterface
  • Laravel5DTO implements Jsonable and Arrayable

You can use these to sanitize output before you send it to a view, eg:

$models = Model::all();
$output = [];
foreach($models as $model)
    $output[] = new Laravel4DTO([
        'name' => $model->name,
        'paid' => $model->payments->sum('payment_amount'),
        ...
    ]);
return new Collection($output);

Installation

Install the package via Composer. Edit your composer.json file as follows:

"require": {
    "kumuwai/data-transfer-object": "dev-master"
}

Next, update Composer from the terminal:

composer update

TODO

None at this time

You can’t perform that action at this time.