PHP code example of kwai / jsonapi

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

    

kwai / jsonapi example snippets


use Kwai\JSONAPI;

#[JSONAPI/Resource(type: 'people')]
class Person 
{
    public function __construct(
        // We need at least an id property.
        private string $id,
    )
}

use Kwai\JSONAPI;

#[JSONAPI/Resource(type: 'people')]
class Person 
{
    public function __construct(
        private string $id,
        #[JSONAPI/Attribute]
        private string $name,
        private int $age,
    ) {
    }
    
    #[JSONAPI/Attribute(name: 'age')]
    public function getAge(): int
    {
        return $this->age;
    }
}

$person = new Person(
    id: '1',
    name: 'Jigoro Kano',
    age: 77,
);

#[JSONAPI\Resource(type:'athletes')]
class Athlete
{
    public function __construct(
        private string $id,
        #[JSONAPI\Attribute]
        private string $name,
        #[JSONAPI\Relationship]
        private Country $country,
    ) {
    }
}

$country = new Country(
    id: '1',
    code: 'BEL',
);
$athlete = new Athlete(
    id: '1',
    name: 'Ingrid Berghmans',
    country: $country
)

use Kwai\JSONAPI;

$person = new Person(
    id: '1',
    name: 'Jigoro Kano',
    age: 77,
);

try {
    $jsonapi = JSONAPI\Document::createFromObject($person)->serialize();
    // Send $jsonapi to the client...
} catch (JSONAPI\Exception $e) {
    // An exception occurred while serializing the PHP object.
}

    try {
        $jsonapi =
            JSONAPI\Document::createFromObject($person)
                ->setMeta('count', 1)
                ->serialize();
    } catch (JSONAPI\Exception $e) {
        // Handle exception...
    }