PHP code example of attus / jsonapi_response
1. Go to this page and download the library: Download attus/jsonapi_response 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/ */
attus / jsonapi_response example snippets
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\jsonapi_response\JsonapiEntityResponseInterface;
class MyController extends ControllerBase {
private $_jsonapiResponseEntity;
public function __construct(JsonapiEntityResponseInterface $jsonapiResponseEntity) {
$this->_jsonapiResponseEntity = $jsonapiResponseEntity;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('jsonapi_response.entity'),
);
}
/**
* A single entity in JSON:API Format
*/
public function getMyEntity(): CacheableResponseInterface
{
$entity = $this->getEntityForResponse();
$response = $this->_jsonapiResponseEntity->entityIndividualResponse($entity);
$cache = new CacheableMetadata();
$cache->setCacheMaxAge(0);
$response->addCacheableDependency($cache);
return $response;
}
/**
* An entity collection in JSON:API Format
*/
public function getMyEntityCollection(): CacheableResponseInterface
{
$entities = $this->getEntitiesForResponse();
return $this->_jsonapiResponseEntity->entityCollectionResponse($entities);
}
/**
* An entity collection in JSON:API Format with