Esempio n. 1
0
 * the collection you want to send out
 * 
 * normally, you'd fetch this from a database
 */
require 'dataset.php';
$users = array(new user(1), new user(2), new user(42));
$collection = array();
foreach ($users as $user) {
    $resource = new jsonapi\resource($type = 'user', $user->id);
    $resource->set_self_link('/user/' . $user->id);
    $resource->fill_data($user);
    if ($user->id == 42) {
        $ship = new jsonapi\resource('ship', 5);
        $ship->add_data('name', 'Heart of Gold');
        $ship->set_self_link('/ship/5');
        $resource->add_relation('ship', $ship);
    }
    $collection[] = $resource;
}
/**
 * building up the json response
 * 
 * you can set arrays, single data points, or whole objects
 * objects are converted into arrays using their public keys
 */
$jsonapi = new jsonapi\collection($type = 'user');
$jsonapi->fill_collection($collection);
/**
 * sending the response
 */
$jsonapi->send_response();
Esempio n. 2
0
 /**
  * @param $linkPrefix
  * @return JsonApi\resource
  * @throws \Exception
  */
 protected function prepareJsonApiResource($linkPrefix = '/forest')
 {
     $toReturn = new JsonApi\resource($this->getCollection()->getName(), $this->getId());
     $toReturn->fill_data($this->getAttributes());
     foreach ($this->getRelationships() as $relationship) {
         $resource = new JsonApi\resource($relationship->getType(), $relationship->getId());
         $toReturn->add_relation($relationship->getType(), $resource);
     }
     foreach ($this->getIncluded() as $resource) {
         $toInclude = new JsonApi\resource($resource->getCollection()->getName(), $resource->getId());
         // NOTE : alsvanzelf/jsonapi takes current request to build set_self_link
         // => included resources must set it "manually"
         $toInclude->set_self_link($linkPrefix . '/' . $resource->getCollection()->getName() . '/' . $resource->getId());
         $toInclude->fill_data($resource->getAttributes());
         $toReturn->add_included_resource($toInclude);
     }
     return $toReturn;
 }