Closed newtonianb closed 10 years ago
Make yourself a base presenter and have it implement Illuminate\Support\Contracts\ArrayableInterface and make toArray() call $this->object->toArray(). Then you will just have to do echo $users;
So...
<?php namespace WhateverNamespace;
use Robbo\Presenter\Presenter;
use Illuminate\Support\Contracts\ArrayableInterface;
class Base extends Presenter implements ArrayableInterface {
public function toArray()
{
// Should probably do some checks here for array, arrayable interface etc
return $this->object->toArray();
}
}
See if that works. Also don't close this issue, when I get time I will add in toJson, toArray and __toString, this will be my reminder.
Fantastic! That worked for the array of users thank you very much!
Question though, why do I still have to do user: <?php echo $user->getObject(); ?>,
for the one user? If I don't do getObject() I get. Object of class UserPresenter could not be converted to string
For that one to work you need to implement __toString and toJson.
__toString() needs to simply call toJson() and toJson() needs to call $this->object->toJson()
Did I mention that you rock! Thank you
public function __toString() {
return $this->toJson();
}
public function toJson() {
return $this->object->toJson();
}
public function toArray() {
// Should probably do some checks here for array, arrayable interface etc
return $this->object->toArray();
}
I'm trying to output JSON and include my presenter values, and I'm using these methods with a base presenter, but no dice. Does this still work with the latest version?
I'm trying to encode my user object to json so I can pass it to my javascript variable. The problem since it is getting converted to a UserPresenter in my view I'm having some issues.
For one user I can just do $user->getObject() and that get's properly encoded in my view however I have a problem when it's a collection or array of users (essentiall UserPresenters in the view), how would i do it in a clean way?
For one user I do $user->getObject()
result
However how do I do it if it's a collection of users?
result
This is the only way I got it working but it's so nasty
result