PHP code example of mixerapi / hal-view

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

    

mixerapi / hal-view example snippets


# src/Application.php
public function bootstrap(): void
{
    // other logic...
    $this->addPlugin('MixerApi/HalView');
}

# src/Controller/AppController.php
public function initialize(): void
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
    // other logic...
}


declare(strict_types=1);

namespace App\Model\Entity;

use Cake\ORM\Entity;
use MixerApi\HalView\HalResourceInterface;
use Cake\Datasource\EntityInterface;

class Actor extends Entity implements HalResourceInterface
{
    // your various properties and logic

    /**
     * @param EntityInterface $entity
     * @return array|\string[][]
     */
    public function getHalLinks(EntityInterface $entity): array
    {
        return [
            'self' => [
                'href' => '/actors/' . $entity->get('id')
            ]
        ];
    }
}

#src/Controller/ActorsController.php
public function view($id = null)
{
    $this->request->allowMethod('get');
    $actor = $this->Actors->get($id, [
        'contain' => ['Films'],
    ]);
    $this->set('actor', $actor);
    $this->viewBuilder()->setOption('serialize', 'actor');
}

#src/Controller/ActorsController.php
public function index()
{
    $this->request->allowMethod('get');
    $actors = $this->paginate($this->Actors, [
        'contain' => ['Films'],
    ]);
    $this->set(compact('actors'));
    $this->viewBuilder()->setOption('serialize', 'actors');
}

use MixerApi\HalView\JsonSerializer;

# json
$json = (new JsonSerializer($data))->asJson(JSON_PRETTY_PRINT); // asJson argument is optional

# array
$hal = (new JsonSerializer($data))->getData();

# json with `_links.self.href` and pagination meta data
use Cake\Http\ServerRequest;
use Cake\View\Helper\PaginatorHelper;
$json = (new JsonSerializer($data, new ServerRequest(), new PaginatorHelper()))->asJson();