PHPackages                             deefour/transformer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. deefour/transformer

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

deefour/transformer
===================

Transform raw input data into consistent, immutable PHP objects

1.7.2(6y ago)1251.0k↓48.6%22MITPHPPHP &gt;=5.5.0

Since Apr 22Pushed 6y ago1 watchersCompare

[ Source](https://github.com/deefour/transformer)[ Packagist](https://packagist.org/packages/deefour/transformer)[ Docs](https://github.com/deefour/interactor)[ RSS](/packages/deefour-transformer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (27)Used By (2)

Transformer
===========

[](#transformer)

[![Build Status](https://camo.githubusercontent.com/64ba550bca0eccb1f87063cd9bdad187b689322f6fe92213a12d7ce96e621b47/68747470733a2f2f7472617669732d63692e6f72672f646565666f75722f7472616e73666f726d65722e737667)](https://travis-ci.org/deefour/transformer)[![Total Downloads](https://camo.githubusercontent.com/7653518852eab3bec95b6a535ea73df9605159f7c8fb65eb0355512215400083/68747470733a2f2f706f7365722e707567782e6f72672f646565666f75722f7472616e73666f726d65722f642f746f74616c2e737667)](https://packagist.org/packages/deefour/transformer)[![Latest Stable Version](https://camo.githubusercontent.com/dbb129402c9cc7164b2f9d7b79875e6941f01eb7e34fcd587b430dbf76aa9c17/68747470733a2f2f706f7365722e707567782e6f72672f646565666f75722f7472616e73666f726d65722f762f737461626c652e737667)](https://packagist.org/packages/deefour/transformer)[![License](https://camo.githubusercontent.com/71a597571ee789711f853c3f581d08771be659e39fe9b067fb43663ba96e69d7/68747470733a2f2f706f7365722e707567782e6f72672f646565666f75722f7472616e73666f726d65722f6c6963656e73652e737667)](https://packagist.org/packages/deefour/transformer)

Transform raw input data into consistent, immutable data transfer objects.

Getting Started
---------------

[](#getting-started)

Run the following to add Transfromer to your project's `composer.json`. See [Packagist](https://packagist.org/packages/deefour/transformer) for specific versions.

```
composer require deefour/transformer
```

**`>=PHP5.5.0` is required.**

Overview
--------

[](#overview)

- All transformers extend the abstract `Deefour\Transformer\Transformer` class.
- A tranformer accepts a single array of data during instantiation.
- Attributes on the input source can be cast into specific types.
- A getter can be created for each attribute to define a transformation of it's raw value.
- Methods can be created to provide additional, custom attributes.
- The input source on the transformer is immutable.
- The transformer can be queried to retrieve transformed versions of individual attributes from the source data or the entire data set.

Example
-------

[](#example)

Let's say the following input data is submitted via a `POST` request to create a new `Book`.

```
$input = [
    'title'            => 'a whole new world',
    'price'            => '29.95',
    'publication_date' => '2010-12-09',
    'author'           => 'Jason Daly',
];
```

Let's also say that we want to be sure the title of the book has been properly titleized, the price is a float value, and the publication date is a `Carbon\Carbon` datetime object. The attributes of this raw `$input` can be formatted in a specific, consistent format using a transformer.

```
use Deefour\Transformer\Transformer;
use Carbon\Carbon;

class BookTransformer extends Transformer
{
    protected $casts [
        'price' => 'float',
    ];

    public function title()
    {
        return trim(ucwords($this->raw('title')));
    }

    public function publicationDate()
    {
        return Carbon::parse($this->raw('publication_date'));
    }
}
```

The methods are optional, each having public visibility and being named after a camel-cased version of an attribute. These methods will be called whenever those attributes are requested from the transformer.

```
$transform = new BookTransformer($input);

$transform->get('title');            //=> 'A Whole New World'
$transform->get('price');            //=> 29.95 (cast to a float)
$transform->get('publication_date'); //=> Carbon\Carbon instance
```

### Casts

[](#casts)

A protected `$casts` property can be added to a transformer, composed of attribute names as its keys and the scalar type the attribute should be cast into by the transformer as its values. This mapping will be checked as attributes are returned from a transformer, casting them to the desired type.

```
class BookTransformer extends Transformer
{
    protected $casts [
        'price' => 'float',
    ];
}

$attributes  = [ 'price' => '3.23' ];
$transformer = new BookTransformer($attributes);

$transformer->price; //=> 3.23 (cast to a float)
```

> **Note:** Casts to type 'object' and 'array' will be converted to JSON using [`json_encode`](https://php.net/json_encode).

### Hiding Raw Input

[](#hiding-raw-input)

A protected `$hidden` property can be added to a transformer, listing attributes that will be omitted from bulk requests for information like `toArray()`, `all()`, and `jsonSerialize()`.

```
class CarTransformer extends Transformer
{
    protected $hidden = [ 'cylinders' ];
}

$attributes  = [ 'make' => 'Subaru', 'model' => 'WRX', 'cylinders' => 4 ];
$transformer = new Transformer($attributes);

$transformer->cylinders; //=> 4
$transformer->has('cylinders'); //=> true
$transformer->all(); //=> [ 'make' => 'Subaru', 'model' => 'WRX' ]
$transform->except('make'); // [ 'model' => 'WRX' ]
```

### Fallbacks (Default Values)

[](#fallbacks-default-values)

A protected `$fallbacks` property can be added to a transformer, composed of attribute names as its keys and default values as its values. This mapping will be checked as attributes are requested from a transformer but cannot be found on the source data **or whose value is `NULL`**.

#### Accepting `NULL` Values

[](#accepting-null-values)

If an attributes on the source with a `NULL` value should generally be accepted in favor of a default value in the `$fallbacks` mapping, this can be enabled for the lifecycle of a request on all transformers by running the following:

```
Deefour\Transformer\Transformer::preferNullValues();
```

To illustrate the difference:

```
class BookTransformer extends Transformer
{
    protected $fallbacks [
        'category' => 'Miscellaneous',
    ];
}

$attributes  = [ 'category' => null ];
$transformer = new BookTransformer($attributes);

$transformer->category; //=> Miscellaneous

Deefour\Transformer\Transformer::preferNullValues();

$transformer->category; //=> null
```

### Method Attributes

[](#method-attributes)

Public methods marked with `@attribute` in their docblock are be treated as attributes on the transformer's `$attributes` source.

```
class BookTransformer extends Transformer
{
    /**
     * Is the book considered old?
     *
     * @attribute
     * @return string
     */
    public function isOld()
    {
        return $this->publication_date < Carbon::now()->subYears(10);
    }

    /**
     * Is the book nonfiction?
     *
     * @return boolean
     */
    public function internalSlug()
    {
        return sha1($this->title . (string)$this->publication_date);
    }
}
```

The `isOld` method is marked with an `@attribute` annotation in the docblock, causing the transformer to behave as though an `is_old` attribute exists on the source data. `internalSlug()` can be called directly, but it will not be treated as some `internal_slug` attribute because it has not been marked properly with a docblock annotation.

```
$transform = new BookTransformer([ 'title' => 'A Whole New World' ]);

$transform->get('title');          //=> 'A Whole New World'
$transform->get('is_old')          //=> false
$transformer->get('internal_slug') //=> null

$transform->all();                 //=> [ 'title' => 'A Whole New World', 'is_old' => false ]
```

Accessing Data
--------------

[](#accessing-data)

Individual transformed attributes can be retrieved with `get()`.

```
$transform->get('title');
```

A magic `__get()` implementation provides property access to the transformed attributes

```
$transform->title;
```

A magic `__call()` implementation provides method access

```
$transformer->title();
```

The existince of a property can be checked through `__isset()` or the api

```
isset($transform->title);

$transform->exists('title');
$transform->has('title');
$transform->contains('title');
```

Transformers also implement `ArrayAccess` *(attempting to set or unset throws an exception)*.

```
$transform['title'];
```

All transformed attributes can be retrieved at once.

```
$transform->all();
```

and a specific set of keys can be plucked all at once.

```
$transform->only('title', 'price', 'internal_slug'); //=> [ 'title' => 'A Whole New World', 'price' => 29.95, 'internal_slug' => null ]
```

```
$transform->intersect('title', 'price', 'internal_slug'); //=> [ 'title' => 'A Whole New World', 'price' => 29.95 ]
```

```
$transform->except('secret_key'); //=> everything except the 'secret_key' attribute.
$transform->omit('secret_key');
```

The `JsonSerializable` interface is also implemented.

```
json_encode($transform); //=> "{'title':'A Whole New World', 'price':29.95, 'publication_date':'2010-12-09 00:00:00', 'author':'Jason Daly'}"
```

Individual raw attributes or the entire raw source can be retrieved.

```
$transform->raw('title'); //=> 'a whole new world'
$transform->raw(); //=>  [ 'title' => 'a whole new world', 'price' => '29.95', 'publication_date' => '2010-12-09', 'author' => 'Jason Daly' ]
```

A default value can be provided to `get()` as a second parameter. If the default is a callable, it will be evaluated before returning.

```
$transformer->get('invalid-attribute', 'Not Available'); //=> 'Not Available'
$transformer->get('invalid-attribte', function() { return 'Oops!'; }); //=> 'Oops!'
```

Mutable Transformers
--------------------

[](#mutable-transformers)

In the base transformer, `__set()`, `offsetSet`, and `offsetUnset` are all null methods. This (lack of) behavior keeps the underlying source data immutable.

A `MutableTransformer` class exists which does implement these methods, allowing additional properties to be added to, or existing properties to be modified on the transformer instance.

The `__call()` method can also be used to set/modify attributes on the transformer.

```
$transformer = new MutableTransformer([ 'foo' => '1234' ]);

$transformer->foo('abcd');

$transformer->get('foo'); //=> 'abcd'
```

Instantiation and data access are otherwise identical to the base transformer.

### Tracking Changes

[](#tracking-changes)

When an attribute is modified on a mutable transformer, it's original value is maintained. The transformer can be queried to determine if an attribute has been modified after construction or to retrieve a list of changes.

```
$transformer = new MutableTransformer([ 'foo' => 'AAA', 'bar' => 'BBB' ]);

$transformer->isDirty(); //=> false

$transformer->foo = 'new value';

$transformer->isDirty(); //=> true
$transformer->dirty(); //=> [ 'foo' ]
$transformer->get('foo'); //=> 'new value'
$transformer->original('foo'); //=> 'AAA'

$transformer->changes(); //=> [ 'foo' => 'new value' ]
```

Contribute
----------

[](#contribute)

- Issue Tracker:
- Source Code:

Changelog
---------

[](#changelog)

#### 1.7.0 - March 2, 2017

[](#170---march-2-2017)

- Added support for hidden attributes from bulk accessors.

#### 1.6.0 - February 14, 2017

[](#160---february-14-2017)

- `jsonSerialize()` will now call `jsonSerialize()` on attributes implementing `JsonSerializable`, allowing transformers to recursively be encoded to JSON.

#### 1.5.0 - October 20, 2016

[](#150---october-20-2016)

- Rename `default()` to `fallback()` throughout the library for compatibility with all PHP versions.

#### 1.4.0 - October 20, 2016

[](#140---october-20-2016)

- Support for default attributes being set on a class' new `$fallbacks` property. This set of defaults will be checked when an attribute is requested which does not exist or is `NULL`. Thanks to [@dgallinari](https://github.com/dgallinari) [\#2](https://github.com/deefour/transformer/pull/2)

#### 1.3.0 - October 16, 2016

[](#130---october-16-2016)

- The `@attribute` annotation only needs to be set on methods you wish to be treated as attributes that are not camel-cased versions of attributes that exist on the raw input source.
- `omit()` and `without()` have been added as aliases for `except()`.
- `has()` and `contains()` have been added as aliases for `exists()`.

#### 1.0.1 - October 29, 2015

[](#101---october-29-2015)

- Added `except()` method.

#### 1.0.0 - October 7, 2015

[](#100---october-7-2015)

- Release 1.0.0.

#### 0.4.0 - September 7, 2015

[](#040---september-7-2015)

- Support added for "attribute methods" - methods who's snake-cased equivalent name is not present in the `$attributes` source, but who are still treated as any other attribute that *is* present in the `$attributes` source.
- `protected` methods that should not be treated as "attribute methods" should now be tagged `@internal` in their docblock.

#### 0.3.0 - September 4, 2015

[](#030---september-4-2015)

- New change tracking, inspired by [yammer/model\_attribute](https://github.com/yammer/model_attribute)

#### 0.2.6 - June 5, 2015

[](#026---june-5-2015)

- Now following PSR-2.

#### 0.2.5 - June 3, 2015

[](#025---june-3-2015)

- New `__call()` functionality providing magic method access to attributes.
- `get()` now handles default values, including closures.

#### 0.2.4 - June 2, 2015

[](#024---june-2-2015)

- Fixed bugs in the `only()` method related to nested attributes.

#### 0.2.2 - May 30, 2015

[](#022---may-30-2015)

- `raw()` will now return the complete, non-transformed source if no `$attribute` is specified.
- `MutableTransformer` can now be instantiated without any arguments passed to the constructor.

#### 0.2.1 - May 25, 2015

[](#021---may-25-2015)

- Improved code formatting.

#### 0.2.0 - May 5, 2015

[](#020---may-5-2015)

- Made the base transformer a regular class (it used to be abstract).
- Added new `MutableTransformer`.

#### 0.1.0 - April 22, 2015

[](#010---april-22-2015)

- Initial release.

License
-------

[](#license)

Copyright (c) 2016 [Jason Daly](http://www.deefour.me) ([deefour](https://github.com/deefour)). Released under the [MIT License](http://deefour.mit-license.org/).

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~60 days

Recently: every ~213 days

Total

26

Last Release

2527d ago

Major Versions

0.4.1 → 1.0.02015-10-07

### Community

Maintainers

![](https://www.gravatar.com/avatar/0a2bddbe9f87813e53e82c1799b460513ede9f96a1d85ad7c186c0692a6f0762?d=identicon)[deefour](/maintainers/deefour)

---

Top Contributors

[![deefour](https://avatars.githubusercontent.com/u/14762?v=4)](https://github.com/deefour "deefour (93 commits)")

---

Tags

arrayaccessdata-transferphptransformervalue-objectlaraveltransformerdeefourrequest dataraw input

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/deefour-transformer/health.svg)

```
[![Health](https://phpackages.com/badges/deefour-transformer/health.svg)](https://phpackages.com/packages/deefour-transformer)
```

###  Alternatives

[jasonlam604/stringizer

Stringizer is a PHP string manipulation library with support for method chaining and multibyte handling

35110.5k1](/packages/jasonlam604-stringizer)[stephenjude/filament-blog

Filament Blog Builder

20317.8k](/packages/stephenjude-filament-blog)[ralphjsmit/laravel-helpers

A package containing handy helpers for your Laravel-application.

13704.6k2](/packages/ralphjsmit-laravel-helpers)[datomatic/nova-detached-actions

A Laravel Nova tool to allow for placing actions in the Nova toolbar detached from the checkbox selection mechanism.

11229.2k](/packages/datomatic-nova-detached-actions)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
