PHP code example of nocarrier / hal

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

    

nocarrier / hal example snippets



Nocarrier\Hal;

$hal = new Hal('/orders');
$hal->addLink('next', '/orders?page=2');
$hal->addLink('search', '/orders?id={order_id}');

$resource = new Hal(
    '/orders/123',
    array(
        'total' => 30.00,
        'currency' => 'USD',
    )
);

$resource->addLink('customer', '/customer/bob', array('title' => 'Bob Jones <[email protected]>'));
$hal->addResource('order', $resource);
echo $hal->asJson();
echo $hal->asXml();

$hal = new \Nocarrier\Hal();

$hal = new \Nocarrier\Hal('/orders');

$hal = new \Nocarrier\Hal('/orders', ['customerId' => 'CUS1234']);

$hal = \Nocarrier\Hal::fromJson($jsonString);

$hal = \Nocarrier\Hal::fromXml($xmlString);

$hal = \Nocarrier\Hal::fromXml($simpleXMLElement);

$hal = \Nocarrier\Hal::fromJson($jsonString, 5);

$hal = new \Nocarrier\Hal('/orders', ['customerId' => 'CUS1234']);
$hal->asJson();

$hal = new \Nocarrier\Hal('/orders', ['customerId' => 'CUS1234']);
$hal->asJson(true);

$hal = new \Nocarrier\Hal('/orders', ['customerId' => 'CUS1234']);
$hal->asXml(true);

$hal = new \Nocarrier\Hal('/orders');
$hal->setData(['customerId' => 'CUS1234']);
$hal->getData();

$hal = new \Nocarrier\Hal('/orders');
$hal->setData(['customerId' => ['CUS1234', '@type' => 'legacy']]);

$hal = new \Nocarrier\Hal('/orders', ['customerId' => 'CUS1234']);
$hal->addLink('next', '/orders?page=2');
$hal->addLink('search', '/orders?id={order_id}');

$json = '{
     "customerId": "CUS1234",
     "_links": {
         "self": {
             "href": "/orders"
         },
         "next": {
             "href": "/orders?page=2"
         },
         "search": {
             "href": "/orders?id={order_id}"
         }
     }
 }';

$hal = \Nocarrier\Hal::fromJson($json);

foreach($hal->getLinks() as $rel => $links) {
    echo $rel."\n";
    foreach($links as $link) {
        echo (string) $link."\n";
    }
}

$json = '{
     "customerId": "CUS1234",
     "_links": {
         "self": {
             "href": "/orders"
         },
         "next": {
             "href": "/orders?page=2"
         },
         "search": {
             "href": "/orders?id={order_id}"
         }
     }
 }';
$hal = \Nocarrier\Hal::fromJson($json);
foreach($hal->getLink('next') as $link) {
    echo (string) $link."\n";
}

$hal = new \Nocarrier\Hal('/orders', ['customerId' => 'CUS1234']);

$resource = new \Nocarrier\Hal(
    '/orders/123',
    array(
        'total' => 30.00,
        'currency' => 'USD',
    )
);

$resource->addLink('customer', '/customer/bob', array('title' => 'Bob Jones <[email protected]>'));
$hal->addResource('order', $resource);

php composer.phar