thumbtack/ttinjector

This package is abandoned and no longer maintained. No replacement package was suggested.

Construct anything using dependency injection

1.0.4 2016-03-16 01:34 UTC

This package is not auto-updated.

Last update: 2023-09-30 11:06:23 UTC


README

Build Status

This is a simple dependency injector.

It works in two stages. First, you register all the dependencies and describe how they relate to each other. Then, you build an injector out of those dependencies that can inject the values you have added.

Installation

To install, use composer and run:

composer require thumbtack/ttinjector

How to use the injector:

1. Create a Dependencies object:

use TT\injector\Dependencies;

$dependencies = new Dependencies();

2. Add some dependencies:

// Use register_value() to add constant values.
$dependencies->register_value('current_user_id', 12345);

// Use register_factory() to add things you don't want to construct unless used...
$dependencies->register_factory('db_connection', [], function() {
   return Database::Connect();
});

// ...Or things that have dependencies of their own.
$dependencies->register_factory(
   'users_source'
   ['db_connection'],
   function ($db) {
       return function($user_id) use ($db) {
          return $db->query('users')->where_equals('user_id', $user_id);
       };
   }
);

3. Build the injector:

$injector = $dependencies->build_injector();

The build_injector() function will check to make sure there aren't any errors in the dependencies you've set up (missing dependencies or dependency cycles).

Injector objects are immutable.

4. Inject your dependencies!

function current_user($current_user_id, $users_source) {
   return $users_source($current_user_id);
}

$user = $injector->inject('current_user', ['current_user_id', 'users_source']);