robclancy / presenter

Decorate your objects using presenters. Primarily to keep presentation logic out of your models.
MIT License
345 stars 38 forks source link

Usage in the laravel API resource #54

Closed ihorchepurnyi closed 5 years ago

ihorchepurnyi commented 6 years ago

Hi, How can I use presenter class in the API resource

Example: 1) Resource class

class CouponResource extends Resource
{
    public function toArray($request): array
    {
        return [
            'name' => $this->name,
            'url' => $this->url(), // here I try to use the method from the presenter
        ];
    }
}

2) Presenter

use Robbo\Presenter\Presenter;

class CouponPresenter extends Presenter
{
    public function url()
    {
        return $this->id . '-' . $this->name;
    }
}

3) Controller

    public function list(Request $request): AnonymousResourceCollection
    {
        return CouponResource::collection(Coupon::paginate());
    }

4) Model

class Coupon extends Model implements PresentableInterface
{
    public function getPresenter()
    {
        return new CouponPresenter($this);
    }
}
robclancy commented 5 years ago

Like usual this repository doesn't notify me.

I wasn't aware of resources working this way. But you would just have to use things without the delgation "magic". So $this->resource->url() for the presenter method.

However, if you only have an API I wouldn't even recommend using the presenter.