PHPackages                             saritasa/transformers - 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. [API Development](/categories/api)
4. /
5. saritasa/transformers

AbandonedArchivedLibrary[API Development](/categories/api)

saritasa/transformers
=====================

Saritasa custom transformers on top of League/Fractal Library

1.2.2(1y ago)125.8k↓55%12MITPHPPHP &gt;=7.0

Since Apr 3Pushed 1y ago1 watchersCompare

[ Source](https://github.com/Saritasa/php-transformers)[ Packagist](https://packagist.org/packages/saritasa/transformers)[ RSS](/packages/saritasa-transformers/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (10)Dependencies (6)Versions (23)Used By (2)

Data Transformers
=================

[](#data-transformers)

[![PHP Unit](https://github.com/Saritasa/php-transformers/workflows/PHP%20Unit/badge.svg)](https://github.com/Saritasa/php-transformers/actions)[![PHP CodeSniffer](https://github.com/Saritasa/php-transformers/workflows/PHP%20Codesniffer/badge.svg)](https://github.com/Saritasa/php-transformers/actions)[![codecov](https://camo.githubusercontent.com/03a9bc55d84b913dd9b48c95e2b64ed7d1fc5afda965c49934886172b2919fa0/68747470733a2f2f636f6465636f762e696f2f67682f53617269746173612f7068702d7472616e73666f726d6572732f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/Saritasa/php-transformers)[![Release](https://camo.githubusercontent.com/674dd307374bfef1718eba8ee6e5b16cc124c621e3cd5a5f41fda7f75492ec04/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f73617269746173612f7068702d7472616e73666f726d6572732e737667)](https://github.com/Saritasa/php-transformers/releases)[![PHPv](https://camo.githubusercontent.com/bb3317fbc866b519440b6c78ba52188297ad83675398274f993759aabbe4d5e8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f73617269746173612f7472616e73666f726d6572732e737667)](http://www.php.net)[![Downloads](https://camo.githubusercontent.com/d6218ad9d005d85e50bfd3664bc4da022e68d29c285bcca10edbb564ac79a783/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73617269746173612f7472616e73666f726d6572732e737667)](https://packagist.org/packages/saritasa/transformers)

Custom Data transformers on top of [League/Fractal](https://github.com/thephpleague/fractal) library.

See Fractal documentation at

Laravel 5.x/6.x
---------------

[](#laravel-5x6x)

Install the `saritasa/transformers` package:

```
$ composer require saritasa/transformers
```

If you use Laravel 5.4 or less, or 5.5+ with [package discovery](https://laravel.com/docs/5.5/packages#package-discovery) disabled, add the TransformersServiceProvider service provider in `config/app.php`:

```
'providers' => array(
    // ...
    Saritasa\Transformers\TransformersServiceProvider::class,
)
```

This is required for [localization](https://laravel.com/docs/localization) to work properly.

Available transformers
----------------------

[](#available-transformers)

### IDataTransformer

[](#idatatransformer)

Interface to unlink dependency from League/Fractal library. Ensure, that every transformer implementation in this library has this interface.

**Example**:

```
class AnotherTransformerWrapper implements IDataTransformer
{
    public function __construct(IDataTransformer $nestedTransformer) { ... }
}
```

### BaseTransformer

[](#basetransformer)

When you just need to convert model to JSON response via Dingo/Api methods, and have no specific formatting requirements, you can just use **BaseTransformer**. It calls **Arrayable-&gt;toArray()** method. Thus, for Eloquent model result will consist of fields, described as *$visible* and not *$hidden.*Additionally converts fields, enumerated in *$dates* to ISO8061 format.

**Example**:

```
class User extends \Illuminate\Database\Eloquent\Model {
    // "full_name" is a property calculated from first_name and last_name
    protected $visible = ['full_name', 'created_at'];
    protected $hidden = ['email', 'password'];
    protected $dates = ['created_at', 'updated_at', 'birthday'];
}

class UserController extends BaseApiController {
    public function myProfile(): \Dingo\Api\Http\Response {
        $user = $this->user(); // Returns Eloquent model
        return $this->response->item($user, new BaseTransformer);
        // Output will be JSON
        // { "full_name": "Ivan Ivanov", "created_at": "2017-04-12T23:20:50.52Z" }
    }
}

$user = User::find($userId);
```

### ObjectFieldsTransformer

[](#objectfieldstransformer)

Will output requested fields to result, regardless they described as *$hidden* or *$visible* in Eloquent model

**Example**:

```
class User extends \Illuminate\Database\Eloquent\Model {
    // "full_name" is a property calculated from first_name and last_name
    protected $visible = ['full_name', 'created_at'];
    protected $hidden = ['email', 'password'];
    protected $dates = ['created_at', 'updated_at', 'birthday'];
}

class UserController extends BaseApiController {
    public function myProfile(): \Dingo\Api\Http\Response {
        $user = $this->user(); // Returns Eloquent model
        $profileTransformer = new ObjectFieldsTransformer('first_name', 'last_name', 'email', 'birthday');
        return $this->response->item($user, $profileTransformer);
        // Output will be JSON
        // { "first_name": "Ivan", "last_name": "Ivanov", "email": "ivanov@mail.ru", "birthday": "1985-04-12T00:00:00.00Z" }
    }
}

$user = User::find($userId);
```

### CombineTransformer

[](#combinetransformer)

Apply multiple transformers in order of arguments;

**Example**:

```
class UserProfileTransformer extends CombineTransformer
{
    public function __construct()
    {
        parent::__construct(
            new PreloadUserAvatarTransformer(),
            new PreloadUserSettingsTransformer()
        );
    }
}
```

### LimitFieldsTransformer

[](#limitfieldstransformer)

Result will first apply -&gt;toArray() method (which acts, respecting Eloquent's *$visible* and *$hidden* fields), then limits output to selected fields. This, hidden fields will not get in output, even if listed.

**Example**:

```
class User extends \Illuminate\Database\Eloquent\Model {
    protected $visible = ['full_name', 'created_at'];
    protected $hidden = ['email', 'password'];
    protected $dates = ['created_at', 'updated_at', 'birthday'];
}

class UserController extends BaseApiController {
    public function myProfile(): \Dingo\Api\Http\Response {
        $user = $this->user(); // Returns Eloquent model
        $publicProfileTransformer = new LimitFieldsTransformer('full_name', 'birthday');
        return $this->response->item($user, new BaseTransformer);
        // Output will be JSON
        // { "full_name": "Ivan Ivanov" }
    }
}

$user = User::find($userId);
```

Exceptions
----------

[](#exceptions)

### TransformException

[](#transformexception)

Should be thrown by class, implementing **IDataTransformer**, if it encounters data, that cannot be transformed.

**Example**:

```
function transform(Arrayable $data) {
    if (!$data->author) {
        new TransformException($this, "Author may not be empty");
    }
    // ...
}
```

### TransformTypeMismatchException

[](#transformtypemismatchexception)

Should be thrown, if your transformer expects model of a certain type, but gets another class.

```
class UserTransformer extends BaseTransformer {
    public function transform(Arrayable $model) {
        if (!$model instanceof User) {
            throw new TransformTypeMismatchException($this, User::class, get_class($model));
        }

        return transformUser($model);
    }

    private function transformUser(User $user) {
        ... // Handle strong-typed model
    }
}
```

Utility Classes
---------------

[](#utility-classes)

### DtoModel

[](#dtomodel)

Allows you to use pure DTO models instead of Eloquent, while using Fractal for collection transformation.

Contributing
------------

[](#contributing)

1. Create fork, checkout it
2. Develop locally as usual. **Code must follow [PSR-1](http://www.php-fig.org/psr/psr-1/), [PSR-2](http://www.php-fig.org/psr/psr-2/)** - run [PHP\_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) to ensure, that code follows style guides
3. **Cover added functionality with unit tests** and run [PHPUnit](https://phpunit.de/) to make sure, that all tests pass
4. Update [README.md](README.md) to describe new or changed functionality
5. Add changes description to [CHANGES.md](CHANGES.md) file. Use [Semantic Versioning](https://semver.org/) convention to determine next version number.
6. When ready, create pull request

### Make shortcuts

[](#make-shortcuts)

If you have [GNU Make](https://www.gnu.org/software/make/) installed, you can use following shortcuts:

- `make cs` (instead of `php vendor/bin/phpcs`) - run static code analysis with [PHP\_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)to check code style
- `make csfix` (instead of `php vendor/bin/phpcbf`) - fix code style violations with [PHP\_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)automatically, where possible (ex. PSR-2 code formatting violations)
- `make test` (instead of `php vendor/bin/phpunit`) - run tests with [PHPUnit](https://phpunit.de/)
- `make install` - instead of `composer install`
- `make all` or just `make` without parameters - invokes described above **install**, **cs**, **test** tasks sequentially - project will be assembled, checked with linter and tested with one single command

Resources
---------

[](#resources)

- [Bug Tracker](http://github.com/saritasa/php-transformers/issues)
- [Code](http://github.com/saritasa/php-transformers)
- [Changes History](CHANGES.md)
- [Authors](http://github.com/saritasa/php-transformers/contributors)

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance32

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 86.4% 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 ~127 days

Recently: every ~590 days

Total

22

Last Release

700d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b7632cf2eb5dd552ace9d66947ed6919e19c6a2fdb5dc73b8c71e0f9886ccc83?d=identicon)[saritasa](/maintainers/saritasa)

---

Top Contributors

[![populov](https://avatars.githubusercontent.com/u/3766033?v=4)](https://github.com/populov "populov (57 commits)")[![maxermolenko](https://avatars.githubusercontent.com/u/11438109?v=4)](https://github.com/maxermolenko "maxermolenko (6 commits)")[![hollow-en](https://avatars.githubusercontent.com/u/87475798?v=4)](https://github.com/hollow-en "hollow-en (3 commits)")

---

Tags

api-serverlaravelleague-fractalphpapifractaltransformers

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/saritasa-transformers/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M345](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)[essa/api-tool-kit

set of tools to build an api with laravel

53390.0k](/packages/essa-api-tool-kit)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5021.9k](/packages/simplestats-io-laravel-client)[rapidez/core

Rapidez Core

1823.5k72](/packages/rapidez-core)

PHPackages © 2026

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