Skip to content

Dependency Injection

PJ Dietz edited this page Aug 2, 2014 · 2 revisions

You can inject dependencies into your handlers by passing them into Router::respond (or Router::getResonse). This array will propagate through the routes to your handler, possibly gaining additional array members (like variables from a URI tempate) along the way.

use pjdietz\WellRESTed\Router;

// Prepare some dependencies.
$dependencies = array();

// Let's make a closure that creates and returns an instance of a PDO.
$dependencies["getDatabaseConnection"] = function () {
    $db = new PDO("dsngoodnessgoeshere", "username", "password");
    return $db;
}

// Add in the name for a model class you may use.
$dependencies["catModelClass"] = "\\mysite\\cats\\CatModel";

// Build your router.
$router = new Router();
$router->addRoute(new TemplateRoute("/cats/{id}", "CatHandler"));
// ...add additional routes, etc...

// Dispatch the request to the handler, and pass the dependencies.
$router->respond(array("dependencies" => $dependencies));

// This is the roughly the same as:
// $request = Request::getRequest();
// $response = $this->getResponse($request, array("dependencies" => $dependencies));
// if ($response) {
//    $response->response();
// }

In your CatHandler, you can access the injected dependencies through the $args member. This is also where you will find the {id} variable from the URI template.

use pjdietz\WellRESTed\Handler;

class CatHandler extends Handler
{
    protected function get()
    {
        // Read the {id} from the path (extracted by the TemplateRoute)
        $id = $this->args["id"];

        // Read the dependencies.
        $dependencies = $this->args["dependencies"];
        $db = $dependencies["getDatabaseConnection"]();
        $catModelClass = $dependencies["catModelClass"];

        // Build a model cat using the ID and the dependencies.
        $cat = new $catModelClass($id, $db);

        // Build the response.
        $this->response->setBody(json_encode($cat));
    }
}

Clone this wiki locally