PHP code example of ride / lib-http-jsonapi

1. Go to this page and download the library: Download ride/lib-http-jsonapi library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ride / lib-http-jsonapi example snippets




e ride\library\http\jsonapi\JsonApi;

/**
 * Controller for the blog post API
 */
class BlogPostController {
    
    /**
     * Constructs a new controller
     * @param ride\library\http\jsonapi\JsonApi $api
     */
    public function __construct(JsonApi $api) {
        $this->api = $api;
    }
    
    /**
     * Action to fetch a collection of blog posts
     */
    public function indexAction() {
        $query = $this->api->createQuery($_GET);
        $document = $this->api->createDocument($query);
        
        $blogPosts = $this->getBlogPosts($query, $total);
        
        $document->setResourceCollection(BlogPostResourceAdapter::TYPE, $blogPosts);
        $document->setMeta('total', $total);
        
        http_status_code($document->getStatusCode());
        if ($document->hasContent()) {
            header('Content-Type: ' . JsonApi::CONTENT_TYPE);
    
            echo json_encode($document);
        }
    }
    
    /**
     * Gets the blog posts from the data source
     * @param ride\library\http\jsonapi\JsonApiQuery $query Requested query
     * @param integer $total Total results before pagination
     * @return array
     */
    private function getBlogPosts(JsonApiQuery $query, &$total) {
        // static data as an example
        $blogPosts = array(
            1 => array(
                'id' => 1,
                'title' => 'Lorum Ipsum',
                'author' => array(
                    'id' => 1,
                    'name' => 'John Doe',
                ), 
                'tags' => array(
                    1 => array(
                        'id' => 1,
                        'name' => 'lorum',
                    ),
                    2 => array(
                        'id' => 2,
                        'name' => 'ipsum',
                    ),                    
                ),
            ),
            // ...
        );
        
        // count the total
        $total = count($blogPosts);
        
        // apply pagination
        $blogPosts = array_slice($blogPosts, $query->getOffset(), $query->getLimit(10, 100));

        // return the result
        return $blogPosts;
    }

}



e ride\library\http\jsonapi\JsonApiResourceAdapter;

/**
 * Resource adapter for a blog post
 */
class BlogPostResourceAdapter implements JsonApiResourceAdapter {
   
    /**
     * Type of this resource
     * @var string
     */ 
    const TYPE = 'blog-posts';
    
    /**
     * Gets a resource instance for the provided model data
     * @param mixed $data Data to adapt
     * @param ride\library\http\jsonapi\JsonApiDocument $document Requested document
     * @param string $relationshipPath dot-separated list of relationship names
     * @return ride\library\http\jsonapi\JsonApiResource
     */
    public function getResource($data, JsonApiDocument $document, $relationshipPath = null) {
        $api = $document->getApi();
        $query = $document->getQuery();

        // create the resource for the entry        
        $resource = $api->createResource(self::TYPE, $data['id']);
        $resource->setLink('self', 'http://your-resource-url');
        
        // check for an attribute and set when requested
        if ($query->isFieldRequested(self::TYPE, 'title')) {
            $resource->setAttribute('title', $data['title']);
        }

        // check for a relationship and set when requested        
        if ($query->isFieldRequested(self::TYPE, 'author') && $query->isIncluded($relationshipPath)) {
            // append the field to the relationship path
            $fieldRelationshipPath = ($relationshipPath ? $relationshipPath . '.' : '') . 'author';
            
            // retrieve the resource
            $peopleResourceAdapter = $api->getResourceAdapter('people');
            $author = $peopleResourceAdapter->getResource($data['author'], $document, $fieldRelationshipPath);
            
            // create the relationship 
            $relationship = $api->createRelationship();
            $relationship->setResource($author);
            $relationship->setLink('self', 'http://your-relationship-url');
            $relationship->setLink('related', 'http://your-related-url');
                        
            // add the relationship to your resource
            $resource->setRelationship('author', $relationship);
        }        
        
        // set a relationship collection value        
        if ($query->isFieldRequested(self::TYPE, 'tags') && $query->isIncluded($relationshipPath)) {
            $fieldRelationshipPath = ($relationshipPath ? $relationshipPath . '.' : '') . 'tags';
            $tagResourceAdapter = $api->getResourceAdapter('tags');
            
            $tags = $data['tags'];
            foreach ($tags as $tag) {
                $tags[$tagIndex] = $tagResourceAdapter->getResource($tag, $document);
            }
            
            $relationship = $api->createRelationship();
            $relationship->setResourceCollection($tags);
            $relationship->setLink('self', 'http://your-relationship-url');
            $relationship->setLink('related', 'http://your-related-url');
                                    
            $resource->setRelationship('tags', $relationship);
        }
        
        // return the resource
        return $resource;
    }
    
}