2

I have transformer like down below in the element API.

'transformer' => 'MyTransformerClassName',

Or

'transformer' => new MyTransformerClassName(),

I am going to pass a param like $user through MyTransformerClassName to use in separate Class Like here.

class MyTransformerClassName extends TransformerAbstract
{
    public function transform(Entry $entry)
    {
        return [
            // ... here want to use $user coming from element api
        ];
    }
}

How can I pass the $user variable to the separate transformer class to use it in transform method?

2

Here's how you would do that...

  1. Pass your parameter to the class:
'transformer' => new MyTransformerClassName($user),
  1. Use a constructor to save it as a property:
class MyTransformerClassName extends TransformerAbstract
{
    private $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function transform(Entry $entry) ...
}
  1. Use your property as needed:
class MyTransformerClassName extends TransformerAbstract
{
    private $user;

    public function __construct($user) ...


    public function transform(Entry $entry)
    {
        return [
            'user' => $this->user,
            ...
        ];
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.