Pass an argument to fractal transformer transform

2020-03-18 02:51发布

问题:

Am using fractal package from phpleague. I have a transform class setup like this

    class ConversationTransformer extends TransformerAbstract
    {

        public function transform (Conversation $conversation, $user)
        {
            return [];
        }
    }

however i get missing argument 2 exception for transform when i try to access it

$user = $this->people->get($this->user());
//conversations
$conversations = $this->conversations->user($user);
return $this->fractal->paginatedCollection($conversations, $user, new ConversationTransformer());

回答1:

class ConversationTransformer extends TransformerAbstract
{
    private $params = [];

    function __construct($params = [])
    {
        $this->params = $params;
    }

    public function transform (Conversation $conversation)
    {
        //-- $this->params will be used here            

        return [];
    }
}

Call it with this return:

 return $this->fractal->paginatedCollection($conversations, new ConversationTransformer(['user' => $user]))


标签: php api rest