PHP code example of alsvanzelf / jsonapi

1. Go to this page and download the library: Download alsvanzelf/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/ */

    

alsvanzelf / jsonapi example snippets


use alsvanzelf\jsonapi\ResourceDocument;

$document = new ResourceDocument($type='user', $id=42);
$document->add('name', 'Zaphod Beeblebrox');
$document->add('heads', 2);
$document->sendResponse();

use alsvanzelf\jsonapi\CollectionDocument;
use alsvanzelf\jsonapi\objects\ResourceObject;

$arthur      = new ResourceObject('user', 1);
$ford        = new ResourceObject('user', 2);
$zaphod      = new ResourceObject('user', 42);
$heartOfGold = new ResourceObject('starship', 2001);

$arthur->add('name', 'Arthur Dent');
$ford->add('name', 'Ford Prefect');
$zaphod->add('name', 'Zaphod Beeblebrox');
$heartOfGold->add('name', 'Heart of Gold');

$zaphod->addRelationship('drives', $heartOfGold);

$users    = [$arthur, $ford, $zaphod];
$document = CollectionDocument::fromResources(...$users);
$document->sendResponse();

use alsvanzelf\jsonapi\ErrorsDocument;

$exception = new Exception('That is not valid', 422);

$document = ErrorsDocument::fromException($exception);
$document->sendResponse();

use alsvanzelf\jsonapi\ResourceDocument;
use alsvanzelf\jsonapi\interfaces\ExtensionInterface;

class ExampleExtension implements ExtensionInterface {
	public function getOfficialLink() {
		return 'https://example.org/extension-documentation';
	}
	
	public function getNamespace() {
		return 'foo';
	}
}

$document = new ResourceDocument('user', 42);
$document->add('name', 'Zaphod Beeblebrox');

$extension = new ExampleExtension();
$document->applyExtension($extension);
$document->addExtensionMember($extension, 'bar', 'baz');

$document->sendResponse();