Thursday, 12 December 2013

Total number of results using PhlyRestfully & collections

Anybody using PhlyRestfully has most likely used a paginated result at one time, and sometimes they need to display the total number of results. It's actually rather easy but a bit different then injecting it into the result body....

What you need to do is create a listener that is attached to the SharedEventManager and inserts a header with the total count. In my case i have selected to use the header "X-total-count".

class InjectPaginationCount implements SharedListenerAggregateInterface
{
    /**
     * @var \Zend\Stdlib\CallbackHandler
     */
    protected $listener;

    /**
     * Attach one or more listeners
     *
     * Implementors may add an optional $priority argument; the SharedEventManager
     * implementation will pass this to the aggregate.
     *
     * @param SharedEventManagerInterface $events
     */
    public function attachShared(SharedEventManagerInterface $events)
    {
        $this->listener = $events->attach('PhlyRestfully\ResourceController', 'getList.post', function(Event $event) {

            /**
             * @var $response \Zend\Http\Response
             * @var $paginator \Zend\Paginator\Paginator
             */
            $response  = $event->getTarget()->getResponse();
            $paginator = $event->getParam('collection')->collection;

            if ($paginator instanceof Paginator) {
                $response->getHeaders()->addHeaderLine('X-total-count', $paginator->getTotalItemCount());
            }
        });
    }

    /**
     * Detach all previously attached listeners
     *
     * @param SharedEventManagerInterface $events
     */
    public function detachShared(SharedEventManagerInterface $events)
    {
        $events->detach('PhlyRestfully\ResourceController', $this->listener);
    }
}