PHP code example of alterway / rest-hal-bundle

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

    

alterway / rest-hal-bundle example snippets


Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Alterway\Bundle\RestHalBundle\AwRestHalBundle(),
    );
}

// src/Alterway/DemoBundle/ApiResource/UserResource.php

namespace Alterway\DemoBundle\ApiResource;

use Alterway\Bundle\RestHalBundle\ApiResource\Resource;

class UserResource extends Resource
{
    public function __construct(RouterInterface $router, User $user)
    {
        parent::__construct($router);
        $this->user = $user;
    }

    protected function prepare()
    {
        $this->addLink('next', '/users?page=2');
        $this->addLink('search', '/users?id={user_id}');
    }

    protected function generateUri()
    {
        return $this->router->generate('demo.user', array('id' => 1));
    }
}

// some controller or yours

use Alterway\DemoBundle\ApiResource\UserResource;

/**
 * @Hal(code="200")
 */
public function userWithAnnotateAction(Request $request)
{
    $user = new User;
    return new UserResource($this->get('router'), $user);
}

// some controller or yours

use Alterway\Bundle\HalRestBundle\Response\HalResponse;
use Alterway\DemoBundle\ApiResource\UserResource;

public function userWithoutAnnotateAction(Request $request)
{
    $user = new User;
    $resource = new UserResource($this->get('router'), $user);
    return new HalResponse($resource, 200);
}