Skip to content
On this page

Transformers

Transformers are a useful pattern to delegate model data preparation for presentation in your views or elsewhere in your app.

Model data is often stored in a different format to how the views might need it, or you might have some data in the request that needs converting. For very simple transformations it usually makes sense to handle these within the controller, or to add a mutator / casting method to the model (if you're using one and it fits your use case)

But sometimes this preparation logic starts to feel too substantial, or conceptually awkward and out of scope, to stay within the controller or model. For example, you might not want your model to know too much about your view, or you might find that you need to combine several different models and data sources to compose the data that you need. You might also need to share this same logic across different controllers or services, and want to keep things DRY.

This where the transformer pattern can be useful - it allows you to abstract this data preparation away. The concept is straightforward - feed it the source data and it spits out the data you need, usually as an array.

Some frameworks have the concept of a ViewModel, but we've opted for the more generic Transformer since we often find this pattern very useful outside of any kind of View context.

Example

We're using a transformer in the theme boilerplate for single data pages. In the single and page template controllers, we send the request to it to populate the $context that we eventually send to the view.

php
// app/Transformers/SinglePageTransformer.php
<?php

declare(strict_types=1);

namespace VendorSpace\ReplaceMe\Transformers;

use Forme\Framework\Http\ServerRequest;

class SinglePageTransformer
{
    public function transform(ServerRequest $request): array
    {
        $postId           = $request['postId'];
        $context          = $request['fields'];
        $context['image'] = get_the_post_thumbnail_url($postId);

        return $context;
    }
}

Transformers don't currently implement a specific interface, however you should stick to the general convention of calling this type of service a transformer and placing it in the Transformers directory and namespace.

TIP

If you need something more full featured, we recommend taking a look at League's Fractal.

Code Generation

You can use the codegen cli to create a new transformer.

bash
forme make transformer FooBar

This will create a boilerplate file app/Transformers/FooBarTransformer.php for you.

Made by Moussa Clarke @ Sanders Web Works with ❤️