schulzefelix/laravel-data-transfer-object

Data Transfer Objects with Attribute Casting and Date Mutators.

1.5.2 2022-04-16 17:36 UTC

This package is auto-updated.

Last update: 2024-04-22 17:41:02 UTC


README

Latest Version Software License Build Status StyleCI Latest Version on Packagist Total Downloads

Brings Laravel Attribute Casting and Date Mutators to objects.

Install

Via Composer

$ composer require schulzefelix/laravel-data-transfer-object

Usage

Introduction

Accessors and mutators allow you to format attribute values when you retrieve or set them on object instances.

In addition to custom accessors and mutators, it can also automatically cast date fields to Carbon instances.

Accessors & Mutators

Defining An Accessor

To define an accessor, create a getFooAttribute method on your object where Foo is the "studly" cased name of the column you wish to access. In this example, we'll define an accessor for the first_name attribute. The accessor will automatically be called when attempting to retrieve the value of the slug attribute:

<?php

namespace App;

use SchulzeFelix\DataTransferObject\DataTransferObject;

class Project extends DataTransferObject
{
    /**
     * Get the objects URL friendly slug.
     *
     * @return string
     */
    public function getSlugAttribute()
    {
        return str_slug($value);
    }
}

Defining A Mutator

To define a mutator, define a setFooAttribute method on your object where Foo is the "studly" cased name of the column you wish to access.

<?php

namespace App;

use SchulzeFelix\DataTransferObject\DataTransferObject;

class Project extends DataTransferObject
{
    /**
     * Set the objects's title.
     *
     * @param  string  $value
     * @return void
     */
    public function serTitleAttribute($value)
    {
        $this->attributes['title'] = title_case($value);
    }
}

Date Mutators

By default, it will convert the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class to provide an assortment of helpful methods. You may customize which dates are automatically mutated:

<?php

namespace App;

use SchulzeFelix\DataTransferObject\DataTransferObject;

class Project extends DataTransferObject
{
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'date',
        'deleted_at'
    ];
}

As noted above, when retrieving attributes that are listed in your $dates property, they will automatically be cast to Carbon instances, allowing you to use any of Carbon's methods on your attributes:

return $project->deleted_at->getTimestamp();

Attribute Casting

The $casts property on your object provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the attribute to. The supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.

For example, let's cast the is_index attribute, which was assigned as string to a boolean value:

<?php

namespace App;

use SchulzeFelix\DataTransferObject\DataTransferObject;

class Project extends DataTransferObject
{
    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_index' => 'boolean',
    ];
}

Now the is_index attribute will always be cast to a boolean when you access it, even if the underlying value was set as integer or string:

if ($project->is_index) {
    //
}

Serializing Objects & Collections

Serializing To Arrays

To convert a object and its nested objects and collections to an array, you should use the toArray method. This method is recursive, so all attributes will be converted to arrays:

return $project->toArray();

Serializing To JSON

To convert a object to JSON, you should use the toJson method. Like toArray, the toJson method is recursive, so all attributes and nested objects will be converted to JSON:

return $project->toJson();

Alternatively, you may cast a object or collection to a string, which will automatically call the toJson method on the object or collection:

return (string) $project;

Change log

Please see CHANGELOG for more information what has changed recently.

Testing

$ vendor/bin/phpunit

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email githubissues@schulze.co instead of using the issue tracker.

Credits

A great thanks to Taylor Otwell and all contributors for Laravel.

Modified source comes from the Eloquent Model.

Docs modified from Laravel Docs.

License

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