phly / PhlyRestfully

ZF2 module for creating RESTful JSON APIs using HAL and API-Problem
108 stars 45 forks source link

Allow passing event parameters to the Resource #35

Closed weierophinney closed 11 years ago

weierophinney commented 11 years ago

In discussions with @macnibblet there is a need to be able to pass arbitrary parameters to the Resource object, and the events it triggers. As examples:

To facilitate this, I propose adding the ability to add/set "event parameters" on the Resource object. These would then be passed as parameters to any events triggered by the Resource object.

This will also require adding a getResource() method on the ResourceController so that developers can access the Resource object.

As examples of usage:

// Attaching to a ResourceController event manager's getList.pre event
$events->attach('getList.pre', function ($e) {
    $request = $e->getTarget()->getRequest();
    $from = $request->getQuery('from', false);
    $to = $request->getQuery('to', false);
    $resource = $e->getTarget()->getResource();
    $resource->setEventParams(array(
        'from' => $from,
        'to' => $to,
    ));
});

The above would inject selected query string parameters as event parameters in the resource.

$events->attach('dispatch', function ($e) use ($resourceManager) {
    $routeMatch = $e->getRouteMatch();
    $parentId = $routeMatch->getParam('parentId', false);
    if (!$parentId) {
        // raise an error or return an ApiProblem
    }
    if (!$resourceManager->has($parentId)) {
        // raise an error or return an ApiProblem
    }
    $parent = $resourceManager->get($parentId);
    $e->getTarget()->getResource()->addEventParam('parent', $parent);
}, 10);

The above would test for existence of a parent ID and valid parent ID, and then inject the resource with the parent object.

macnibblet commented 11 years ago

Nice, now i pretty much understand what you meant! Ill try and write something for the weekend.