Skip to content

Instantly share code, notes, and snippets.

@weierophinney
Created September 25, 2014 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weierophinney/2c47c9d59f4a5214f0c3 to your computer and use it in GitHub Desktop.
Save weierophinney/2c47c9d59f4a5214f0c3 to your computer and use it in GitHub Desktop.
One way to return a HAL entity from an Apigility RPC controller.
<?php
public function someAction()
{
$data = doSomeWorkFetchSomeData();
$entity = new \ZF\Hal\Entity($data, $data['id']); // or similar
return new \ZF\ContentNegotiation\ViewModel([
'payload' => $entity,
]);
}
@joipires
Copy link

hal links are not generated using this way. Any suggestions? Thank U.

public function categoryBySlugAction()
{
    $slug = (string) $this->params()->fromRoute('slug', '');        
    if (empty($slug)){
        throw new \Exception("A slug is necessary");
    }
    $data = $this->mapper->fetch($slug);        
    $entity = new Entity($data, $data['id']);
    return new ViewModel(array(
        'payload' => $entity,
    ));
}

getting data

public function findBySlug($slug)
{
    $qb = $this->_em->createQueryBuilder();
    $qb->select(array('c', 's', 'cp', 'cc'));
    $qb->from('Guiaville\Entity\Category', 'c');
    $qb->leftJoin('c.site', 's' );
    $qb->leftJoin('c.parent', 'cp' );
    $qb->leftJoin('c.children', 'cc' );
    $slug = $qb->expr()->literal($slug);
    $qb->where($qb->expr()->eq('c.slug', $slug));

    return $qb->getQuery()->getOneOrNullResult(Query::HYDRATE_ARRAY);
}

@exptom
Copy link

exptom commented Dec 14, 2016

Incase someone else has this problem.
You can use the Hal plugin that the Rest controllers use to generate Hal entities containing links:

<?php
    public function anRpcAction()
    {
        $entity = $this->getEntityFromSomewhere();

        $route = $this->getEvent()->getRouteMatch();

        return new ViewModel([
            'payload' => $this->Hal()->createEntity($entity, $route, $route->getMatchedRouteName())
        ]);
    }

@Nguimjeu
Copy link

If you havn't defined a REST service for the entity you want to return, you might need to configure the metadata map by hand

'zf-hal' => [
        'metadata_map' => [
            'User' => [
                'route_name' => 'api.rest.user',
                'entity_identifier_name' => 'username',
                'route_identifier_name' => 'user_id',
                'hydrator' => 'Zend\Stdlib\Hydrator\ObjectProperty',
            ],
        ],
    ],

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment