Overview

Slim has a built-in resource locator, providing an easy way to inject objects into a Slim app, orto override any of the Slim app’s internal objects (e.g. Request, Response, Log).

Injecting simple values

If you want to use Slim as a simple key-value store, it is as simple as this:

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->foo = 'bar';

Now, you can fetch this value anywhere with $app->foo and get its value bar.

Using the resource locator

You can also use Slim as a resource locator by injecting closures that define howyour desired objects will be constructed. When the injected closure is requested, it willbe invoked and the closure’s return value will be returned.

  1. <?php
  2. $app = new \Slim\Slim();
  3. // Determine method to create UUIDs
  4. $app->uuid = function () {
  5. return exec('uuidgen');
  6. };
  7. // Get a new UUID
  8. $uuid = $app->uuid;

Singleton resources

Sometimes, you may want your resource definitions to stay the same each time they are requested(i.e. they should be singletons within the scope of the Slim app). This is easy to do:

  1. <?php
  2. $app = new \Slim\Slim();
  3. // Define log resource
  4. $app->container->singleton('log', function () {
  5. return new \My\Custom\Log();
  6. });
  7. // Get log resource
  8. $log = $app->log;

Every time you request the log resource with $app->log, it will return the same instance.

Closure resources

What if you want to literally store a closure as the raw value and not have it invoked? You can do thatlike this:

  1. <?php
  2. $app = new \Slim\Slim();
  3. // Define closure
  4. $app->myClosure = $app->container->protect(function () {});
  5. // Return raw closure without invoking it
  6. $myClosure = $app->myClosure;