Skip to content

Routines as events #82

@nickl-

Description

@nickl-

What if routines were events? Since they

At first purely cosmetic refactor imploring the use of a Dispatcher pattern instead of Abstract Routine doing the work.

<?php

namespace Respect\Rest\Routines;

class RoutineDispatcher
{
    private static $handlers = array();

    public static function addHandler(string $type, Routinable $routine)
    {
        if (!is_array(static::$handlers[$type]))
            static::$handlers[$type] = array();
        static::$handlers[$type][] = $routine;
    }

    public static function dispatch(string $type, string $method, array $args) {
        foreach (static::$handler[$type] as $routine)
            call_user_func_array(array($routine, $method), $args);
    }

}

class Request
{
    /** ...  */
    public function routineCall($type, $method, AbstractRoutinable $routine, &$routeParamsValues)
    {
        /** ... */
        $callbackParameters = $routeParamsValues;

        return RoutineDispatcher::dispatch($type, $method, array($this, $callbackParameters));
    }
}

class AbstractRoute
{
    public function appendRoutine(Routinable $routine)
    {
        RoutineDispatcher::addHandler(get_class($routine), $routine);
        return $this;
    }

}

Making things a tad more structured, understandable logical and already adding the benefit of multiple handlers per type which will allow for this:

$r3->get('/about', function() {
    return array('v' => 2.0);
})->accept(array(
    'text/html' => function($data) {
        list($k,$v)=each($data);
        return "<strong>$k</strong>: $v";
    }
))->accept(array(
    'application/json' => 'json_encode'
));

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions