robclancy / presenter

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

Nested presenters (a.k.a Presenting Eloquent relationships) #9

Closed alexwhitman closed 11 years ago

alexwhitman commented 11 years ago

I'm using Presenter with some Eloquent models which works fine for the 'top-level' model, but relationships aren't converted to a presenter.

For example, if I have classes defined as:

class GenericPresenter extends Robbo\Presenter\Presenter {
    public function presentTest()
    {
        return 'test';
    }
}

class User extends Eloquent implements Robbo\Presenter\PresentableInterface {
    public function department()
    {
        return $this->hasOne('Department');
    }

    public function getPresenter()
    {
        return new GenericPresenter($this);
    }
}

class Department extends Eloquent implements Robbo\Presenter\PresentableInterface {
    public function getPresenter()
    {
        return new GenericPresenter($this);
    }
}

In a controller:

$users = User::with('department')->get();
return View::make('view')->with('users', $users);

In the view:

@foreach ($users as $user)
    {{{ $user->test }}} - {{{ $user->department->test }}}
@endforeach

prints test - because $user->department isn't an instance of GenericPresenter.

Now obviously my use case is Eloquent specific, but it would be useful if there was a way of defining relationships/attributes which should also be made presentable if they implement PresentableInterface.

robclancy commented 11 years ago

Closed. Spoke about this on IRC.

maktouch commented 10 years ago

Hi, could I have details of what was spoken about this on IRC?

Facing the same problem - trying to find the best way to solve it.

Cheers.

robclancy commented 10 years ago

I can't remember. Basically you need to decorate it yourself I can't magically tell it to use a presenter instance in that way. When you want the presenter just call ->getPresenter() yourself or something. Give me a more specific use case and I can tell you how I would do it.

maktouch commented 10 years ago

Cool. That's how I was doing it - doesn't look pretty but it works.

Cheers for that!