vendredi 17 mars 2017

create differen objects based on multiple parameters

I have rest api. I need to create presentation (DTO) object, but the construction of this object depends on request - it differs in 15%. I wonder what pattern should I use.

My case:

//presentation-DTO
class Item {
    private $name;
    private $price;
    private $tags;
    private $liked; //is Liked by logged user
    ...

    public function __construct(Item $item, bool $liked, ...)
    {
        $this->name = $item->getName();
        $this->price = $item->getPrice();
        $this->tags = $item->getTags();
        $this->liked = $liked;
        ...
    }
}

When user is not logged in - I don't need $liked

When showing list of items - I don't need $tags

And there are more parameters that works as above.

My first idea was to use Builder principle.

$itemBuilder = new ItemBuilder();
$itemBuilder->setItem($item);
...
if($user) {
    $itemBuilder->setUserLiked($userLiked);
    ...
}
return $itemBuilder->build();

It solves my problem with too many parameters in constructor.

But still, I also don't need all parameters to be constructed - eg. I don't need tags (on lists). As I use lazy load, I don't want my dto constructor to call them.

So I thought, maybe Factory.. but then my problem with too many (and optional) parameters is returning.

How will you solve this?

Aucun commentaire:

Enregistrer un commentaire