项目作者: amphp

项目描述 :
A recursive dependency injector used to bootstrap and wire together S.O.L.I.D., object-oriented PHP applications.
高级语言: PHP
项目地址: git://github.com/amphp/injector.git
创建时间: 2020-11-25T17:45:13Z
项目社区:https://github.com/amphp/injector

开源协议:MIT License

下载


injector

A recursive dependency injector to bootstrap and wire together S.O.L.I.D., object-oriented PHP applications.

How It Works

Among other things, the injector recursively instantiates class dependencies based on the parameter
type-hints specified in class constructor signatures. This requires the use of Reflection. You may
have heard that “reflection is slow”. Let’s clear something up: anything can be “slow” if you’re
doing it wrong. Reflection is an order of magnitude faster than disk access and several orders of
magnitude faster than retrieving information (for example) from a remote database. Additionally,
each reflection offers the opportunity to cache the results if you’re worried about speed. The injector
caches any reflections it generates to minimize the potential performance impact.

The injector is NOT a Service Locator. DO NOT turn it into one by passing the injector into your
application classes. Service Locator is an anti-pattern; it hides class dependencies, makes code
more difficult to maintain and makes a liar of your API! You should only use an injector for
wiring together the disparate parts of your application during your bootstrap phase.

The Guide

Basic Usage

Advanced Usage

Example Use Cases

Requirements and Installation

  • Requires PHP 8.0 or higher.

Installation

Composer

You may also use composer to include the project as a dependency in your projects composer.json. The relevant package is amphp/injector.

Alternatively require the package using composer cli:

  1. composer require amphp/injector

Basic Usage

To start using the injector, simply create a new instance of the Amp\Injector\Injector (“the Injector”) class:

  1. <?php
  2. $injector = new Amp\Injector\Injector;

Basic Instantiation

If a class doesn’t specify any dependencies in its constructor signature there’s little point in
using the Injector to generate it. However, for the sake of completeness consider that you can do
the following with equivalent results:

  1. <?php
  2. $injector = new Amp\Injector\Injector;
  3. $obj1 = new SomeNamespace\MyClass;
  4. $obj2 = $injector->make(SomeNamespace\MyClass::class);
  5. var_dump($obj2 instanceof SomeNamespace\MyClass); // true
Concrete Type-hinted Dependencies

If a class only asks for concrete dependencies you can use the Injector to inject them without
specifying any injection definitions. For example, in the following scenario you can use the
Injector to automatically provision MyClass with the required SomeDependency and AnotherDependency
class instances:

  1. <?php
  2. class SomeDependency {}
  3. class AnotherDependency {}
  4. class MyClass {
  5. public $dep1;
  6. public $dep2;
  7. public function __construct(SomeDependency $dep1, AnotherDependency $dep2) {
  8. $this->dep1 = $dep1;
  9. $this->dep2 = $dep2;
  10. }
  11. }
  12. $injector = new Amp\Injector\Injector;
  13. $myObj = $injector->make(MyClass::class);
  14. var_dump($myObj->dep1 instanceof SomeDependency); // true
  15. var_dump($myObj->dep2 instanceof AnotherDependency); // true
Recursive Dependency Instantiation

One of the Injector’s key attributes is that it recursively traverses class dependency trees to
instantiate objects. This is just a fancy way of saying, “if you instantiate object A which asks for
object B, the Injector will instantiate any of object B’s dependencies so that B can be instantiated
and provided to A”. This is perhaps best understood with a simple example. Consider the following
classes in which a Car asks for Engine and the Engine class has concrete dependencies of its
own:

  1. <?php
  2. class Car {
  3. private $engine;
  4. public function __construct(Engine $engine) {
  5. $this->engine = $engine;
  6. }
  7. }
  8. class Engine {
  9. private $sparkPlug;
  10. private $piston;
  11. public function __construct(SparkPlug $sparkPlug, Piston $piston) {
  12. $this->sparkPlug = $sparkPlug;
  13. $this->piston = $piston;
  14. }
  15. }
  16. $injector = new Amp\Injector\Injector;
  17. $car = $injector->make(Car::class);
  18. var_dump($car instanceof Car); // true

Injection Definitions

You may have noticed that the previous examples all demonstrated instantiation of classes with
explicit, type-hinted, concrete constructor parameters. Obviously, many of your classes won’t fit
this mold. Some classes will type-hint interfaces and abstract classes. Some will specify scalar
parameters which offer no possibility of type-hinting in PHP. Still other parameters will be arrays,
etc. In such cases we need to assist the Injector by telling it exactly what we want to inject.

Defining Class Names for Constructor Parameters

Let’s look at how to provision a class with non-concrete type-hints in its constructor signature.
Consider the following code in which a Car needs an Engine and Engine is an interface:

  1. <?php
  2. interface Engine {}
  3. class V8 implements Engine {}
  4. class Car {
  5. private $engine;
  6. public function __construct(Engine $engine) {
  7. $this->engine = $engine;
  8. }
  9. }

To instantiate a Car in this case, we simply need to define an injection definition for the class
ahead of time:

  1. <?php
  2. $injector = new Amp\Injector\Injector;
  3. $injector->define(Car::class, ['engine' => 'V8']);
  4. $car = $injector->make(Car::class);
  5. var_dump($car instanceof Car); // true

The most important points to notice here are:

  1. A custom definition is an array whose keys match constructor parameter names
  2. The values in the definition array represent the class names to inject for the specified
    parameter key

Because the Car constructor parameter we needed to define was named $engine, our definition
specified an engine key whose value was the name of the class (V8) that we want to inject.

Custom injection definitions are only necessary on a per-parameter basis. For example, in the
following class we only need to define the injectable class for $arg2 because $arg1 specifies a
concrete class type-hint:

  1. <?php
  2. class MyClass {
  3. private $arg1;
  4. private $arg2;
  5. public function __construct(SomeConcreteClass $arg1, SomeInterface $arg2) {
  6. $this->arg1 = $arg1;
  7. $this->arg2 = $arg2;
  8. }
  9. }
  10. $injector = new Amp\Injector\Injector;
  11. $injector->define(MyClass::class, ['arg2' => 'SomeImplementationClass']);
  12. $myObj = $injector->make(MyClass::class);

NOTE: Injecting instances where an abstract class is type-hinted works in exactly the same way
as the above examples for interface type-hints.

Using Existing Instances in Injection Definitions

Injection definitions may also specify a pre-existing instance of the requisite class instead of the
string class name:

  1. <?php
  2. interface SomeInterface {}
  3. class SomeImplementation implements SomeInterface {}
  4. class MyClass {
  5. private $dependency;
  6. public function __construct(SomeInterface $dependency) {
  7. $this->dependency = $dependency;
  8. }
  9. }
  10. $injector = new Amp\Injector\Injector;
  11. $dependencyInstance = new SomeImplementation;
  12. $injector->define(MyClass::class, [':dependency' => $dependencyInstance]);
  13. $myObj = $injector->make(MyClass::class);
  14. var_dump($myObj instanceof MyClass); // true

NOTE: Since this define() call is passing raw values (as evidenced by the colon : usage),
you can achieve the same result by omitting the array key(s) and relying on parameter order rather
than name. Like so: $injector->define('MyClass', [$dependencyInstance]);

Specifying Injection Definitions On the Fly

You may also specify injection definitions at call-time with Amp\Injector\Injector::make. Consider:

  1. <?php
  2. interface SomeInterface {}
  3. class SomeImplementationClass implements SomeInterface {}
  4. class MyClass {
  5. private $dependency;
  6. public function __construct(SomeInterface $dependency) {
  7. $this->dependency = $dependency;
  8. }
  9. }
  10. $injector = new Amp\Injector\Injector;
  11. $myObj = $injector->make('MyClass', ['dependency' => 'SomeImplementationClass']);
  12. var_dump($myObj instanceof MyClass); // true

The above code shows how even though we haven’t called the Injector’s define method, the
call-time specification allows us to instantiate MyClass.

NOTE: on-the-fly instantiation definitions will override a pre-defined definition for the
specified class, but only in the context of that particular call to Amp\Injector\Injector::make.

Type-Hint Aliasing

Programming to interfaces is one of the most useful concepts in object-oriented design (OOD), and
well-designed code should type-hint interfaces whenever possible. But does this mean we have to
assign injection definitions for every class in our application to reap the benefits of abstracted
dependencies? Thankfully the answer to this question is, “NO.” The Injector accommodates this goal
by accepting “aliases”. Consider:

  1. <?php
  2. interface Engine {}
  3. class V8 implements Engine {}
  4. class Car {
  5. private $engine;
  6. public function __construct(Engine $engine) {
  7. $this->engine = $engine;
  8. }
  9. }
  10. $injector = new Amp\Injector\Injector;
  11. // Tell the Injector class to inject an instance of V8 any time
  12. // it encounters an Engine type-hint
  13. $injector->alias('Engine', 'V8');
  14. $car = $injector->make('Car');
  15. var_dump($car instanceof Car); // bool(true)

In this example we’ve demonstrated how to specify an alias class for any occurrence of a particular
interface or abstract class type-hint. Once an implementation is assigned, the Injector will use it
to provision any parameter with a matching type-hint.

IMPORTANT: If an injection definition is defined for a parameter covered by an implementation
assignment, the definition takes precedence over the implementation.

Non-Class Parameters

All of the previous examples have demonstrated how the Injector class instantiates parameters based
on type-hints, class name definitions and existing instances. But what happens if we want to inject
a scalar or other non-object variable into a class? First, let’s establish the following behavioral
rule:

IMPORTANT: The Injector assumes all named-parameter definitions are class names by default.

If you want the Injector to treat a named-parameter definition as a “raw” value and not a class name,
you must prefix the parameter name in your definition with a colon character :. For example,
consider the following code in which we tell the Injector to share a PDO database connection
instance and define its scalar constructor parameters:

  1. <?php
  2. $injector = new Amp\Injector\Injector;
  3. $injector->share('PDO');
  4. $injector->define('PDO', [
  5. ':dsn' => 'mysql:dbname=testdb;host=127.0.0.1',
  6. ':username' => 'dbuser',
  7. ':passwd' => 'dbpass'
  8. ]);
  9. $db = $injector->make('PDO');

The colon character preceding the parameter names tells the Injector that the associated values ARE
NOT class names. If the colons had been omitted above, the injector would attempt to instantiate classes of
the names specified in the string and an exception would result. Also, note that we could just as
easily specified arrays or integers or any other data type in the above definitions. As long as the
parameter name is prefixed with a :, the injector will inject the value directly without attempting to
instantiate it.

NOTE: As mentioned previously, since this define() call is passing raw values, you may opt to
assign the values by parameter order rather than name. Since PDO’s first three parameters are $dsn,
$username, and $password, in that order, you could accomplish the same result by leaving out the
array keys, like so:
$injector->define('PDO', ['mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass']);

Global Parameter Definitions

Sometimes applications may reuse the same value everywhere. However, it can be a hassle to manually
specify definitions for this sort of thing everywhere it might be used in the app. The injector mitigates
this problem by exposing the Injector::defineParam() method. Consider the following example …

  1. <?php
  2. $myUniversalValue = 42;
  3. class MyClass {
  4. public $myValue;
  5. public function __construct($myValue) {
  6. $this->myValue = $myValue;
  7. }
  8. }
  9. $injector = new Amp\Injector\Injector;
  10. $injector->defineParam('myValue', $myUniversalValue);
  11. $obj = $injector->make('MyClass');
  12. var_dump($obj->myValue === 42); // bool(true)

Because we specified a global definition for myValue, all parameters that are not in some other
way defined (as below) that match the specified parameter name are auto-filled with the global value.
If a parameter matches any of the following criteria the global value is not used:

  • A typehint
  • A predefined injection definition
  • A custom call time definition

Advanced Usage

Instance Sharing

One of the more ubiquitous plagues in modern OOP is the Singleton anti-pattern. Coders looking to
limit classes to a single instance often fall into the trap of using static Singleton
implementations for things like configuration classes and database connections. While it’s often
necessary to prevent multiple instances of a class, the Singleton method spells death to testability
and should generally be avoided. Amp\Injector\Injector makes sharing class instances across contexts a
triviality while allowing maximum testability and API transparency.

Let’s consider how a typical problem facing object-oriented web applications is easily solved by
wiring together your application using the injector. Here, we want to inject a single database connection
instance across multiple layers of an application. We have a controller class that asks for a
DataMapper that requires a PDO database connection instance:

  1. <?php
  2. class DataMapper {
  3. private $pdo;
  4. public function __construct(PDO $pdo) {
  5. $this->pdo = $pdo;
  6. }
  7. }
  8. class MyController {
  9. private $mapper;
  10. public function __construct(DataMapper $mapper) {
  11. $this->mapper = $mapper;
  12. }
  13. }
  14. $db = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
  15. $injector = new Amp\Injector\Injector;
  16. $injector->share($db);
  17. $myController = $injector->make('MyController');

In the above code, the DataMapper instance will be provisioned with the same PDO database
connection instance we originally shared. This example is contrived and overly simple, but the
implication should be clear:

By sharing an instance of a class, Amp\Injector\Injector will always use that instance when
provisioning classes that type-hint the shared class.

A Simpler Example

Let’s look at a simple proof of concept:

  1. <?php
  2. class Person {
  3. public $name = 'John Snow';
  4. }
  5. $injector = new Amp\Injector\Injector;
  6. $injector->share('Person');
  7. $person = $injector->make('Person');
  8. var_dump($person->name); // John Snow
  9. $person->name = 'Arya Stark';
  10. $anotherPerson = $injector->make('Person');
  11. var_dump($anotherPerson->name); // Arya Stark
  12. var_dump($person === $anotherPerson); // bool(true) because it's the same instance!

Defining an object as shared will store the provisioned instance in the Injector’s shared cache and
all future requests to the provider for an injected instance of that class will return the
originally created object. Note that in the above code, we shared the class name (Person)
instead of an actual instance. Sharing works with either a class name or an instance of a class.
The difference is that when you specify a class name, the Injector
will cache the shared instance the first time it is asked to create it.

NOTE: Once the Injector caches a shared instance, call-time definitions passed to
Amp\Injector\Injector::make will have no effect. Once shared, an instance will always be returned for
instantiations of its type until the object is un-shared or refreshed:

Instantiation Delegates

Often factory classes/methods are used to prepare an object for use after instantiation. The injector
allows you to integrate factories and builders directly into the injection process by specifying
callable instantiation delegates on a per-class basis. Let’s look at a very basic example to
demonstrate the concept of injection delegates:

  1. <?php
  2. class MyComplexClass {
  3. public $verification = false;
  4. public function doSomethingAfterInstantiation() {
  5. $this->verification = true;
  6. }
  7. }
  8. $complexClassFactory = function() {
  9. $obj = new MyComplexClass;
  10. $obj->doSomethingAfterInstantiation();
  11. return $obj;
  12. };
  13. $injector = new Amp\Injector\Injector;
  14. $injector->delegate('MyComplexClass', $complexClassFactory);
  15. $obj = $injector->make('MyComplexClass');
  16. var_dump($obj->verification); // bool(true)

In the above code we delegate instantiation of the MyComplexClass class to a closure,
$complexClassFactory. Once this delegation is made, the Injector will return the results of the
specified closure when asked to instantiate MyComplexClass.

Available Delegate Types

Any valid PHP callable may be registered as a class instantiation delegate using
Amp\Injector\Injector::delegate. Additionally you may specify the name of a delegate class that
specifies an __invoke method and it will be automatically provisioned and have its __invoke
method called at delegation time. Instance methods from uninstantiated classes may also be specified
using the ['NonStaticClassName', 'factoryMethod'] construction. For example:

  1. <?php
  2. class SomeClassWithDelegatedInstantiation {
  3. public $value = 0;
  4. }
  5. class SomeFactoryDependency {}
  6. class MyFactory {
  7. private $dependency;
  8. function __construct(SomeFactoryDependency $dep) {
  9. $this->dependency = $dep;
  10. }
  11. function __invoke() {
  12. $obj = new SomeClassWithDelegatedInstantiation;
  13. $obj->value = 1;
  14. return $obj;
  15. }
  16. function factoryMethod() {
  17. $obj = new SomeClassWithDelegatedInstantiation;
  18. $obj->value = 2;
  19. return $obj;
  20. }
  21. }
  22. // Works because MyFactory specifies a magic __invoke method
  23. $injector->delegate('SomeClassWithDelegatedInstantiation', 'MyFactory');
  24. $obj = $injector->make('SomeClassWithDelegatedInstantiation');
  25. var_dump($obj->value); // int(1)
  26. // This also works
  27. $injector->delegate('SomeClassWithDelegatedInstantiation', 'MyFactory::factoryMethod');
  28. $obj = $injector->make('SomeClassWithDelegatedInstantiation');
  29. $obj = $injector->make('SomeClassWithDelegatedInstantiation');
  30. var_dump($obj->value); // int(2)

Prepares and Setter Injection

Constructor injection is almost always preferable to setter injection. However, some APIs require
additional post-instantiation mutations. The injector accommodates these use cases with its
Injector::prepare() method. Users may register any class or interface name for post-instantiation
modification. Consider:

  1. <?php
  2. class MyClass {
  3. public $myProperty = 0;
  4. }
  5. $injector->prepare('MyClass', function($myObj, $injector) {
  6. $myObj->myProperty = 42;
  7. });
  8. $myObj = $injector->make('MyClass');
  9. var_dump($myObj->myProperty); // int(42)

While the above example is contrived, the usefulness should be clear.

Injecting for Execution

In addition to provisioning class instances using constructors, the injector can also recursively instantiate
the parameters of any valid PHP callable.
The following examples all work:

  1. <?php
  2. $injector = new Amp\Injector\Injector;
  3. $injector->execute(function(){});
  4. $injector->execute([$objectInstance, 'methodName']);
  5. $injector->execute('globalFunctionName');
  6. $injector->execute('MyStaticClass::myStaticMethod');
  7. $injector->execute(['MyStaticClass', 'myStaticMethod']);
  8. $injector->execute(['MyChildStaticClass', 'parent::myStaticMethod']);
  9. $injector->execute('ClassThatHasMagicInvoke');
  10. $injector->execute($instanceOfClassThatHasMagicInvoke);
  11. $injector->execute('MyClass::myInstanceMethod');

Additionally, you can pass in the name of a class for a non-static method and the injector will
automatically provision an instance of the class (subject to any definitions or shared instances
already stored by the injector) before provisioning and invoking the specified method:

  1. <?php
  2. class Dependency {}
  3. class AnotherDependency {}
  4. class Example {
  5. function __construct(Dependency $dep){}
  6. function myMethod(AnotherDependency $arg1, $arg2) {
  7. return $arg2;
  8. }
  9. }
  10. $injector = new Amp\Injector\Injector;
  11. // outputs: int(42)
  12. var_dump($injector->execute('Example::myMethod', $args = [':arg2' => 42]));

Dependency Resolution

Amp\Injector\Injector resolves dependencies in the following order:

  1. If a shared instance exists for the class in question, the shared instance will always be returned
  2. If a delegate callable is assigned for a class, its return result will always be used
  3. If a call-time definition is passed to Amp\Injector\Injector::make, that definition will be used
  4. If a pre-defined definition exists, it will be used
  5. If a dependency is type-hinted, the Injector will recursively instantiate it subject to any implementations or definitions
  6. If no type-hint exists and the parameter has a default value, the default value is injected
  7. If a global parameter value is defined that value is used
  8. Throw an exception because you did something stupid

Example Use Cases

Dependency Injection Containers (DIC) are generally misunderstood in the PHP community. One of the
primary culprits is the misuse of such containers in the mainstream application frameworks. Often,
these frameworks warp their DICs into Service Locator anti-patterns. This is a shame because a
good DIC should be the exact opposite of a Service Locator.

The injector is NOT a service locator!

There’s a galaxy of differences between using a DIC to wire together your application versus
passing the DIC as a dependency to your objects (Service Locator). Service Locator (SL) is an
anti-pattern — it hides class dependencies, makes code difficult to maintain and makes a liar of
your API.

When you pass a SL into your constructors it makes it difficult to determine what the class dependencies
really are. A House object depends on Door and Window objects. A House object DOES NOT depend
on an instance of ServiceLocator regardless of whether the ServiceLocator can provide Door and
Window objects.

In real life you wouldn’t build a house by transporting the entire hardware store (hopefully) to
the construction site so you can access any parts you need. Instead, the foreman (__construct())
asks for the specific parts that will be needed (Door and Window) and goes about procuring them.
Your objects should function in the same way; they should ask only for the specific dependencies
required to do their jobs. Giving the House access to the entire hardware store is at best poor
OOP style and at worst a maintainability nightmare. The takeaway here is this:

IMPORTANT: do not use the injector like a Service Locator!

Avoiding Evil Singletons

A common difficulty in web applications is limiting the number of database connection instances.
It’s wasteful and slow to open up new connections each time we need to talk to a database.
Unfortunately, using singletons to limit these instances makes code brittle and hard to test. Let’s
see how we can use the injector to inject the same PDO instance across the entire scope of our application.

Say we have a service class that requires two separate data mappers to persist information to a database:

  1. <?php
  2. class HouseMapper {
  3. private $pdo;
  4. public function __construct(PDO $pdo) {
  5. $this->pdo = $pdo;
  6. }
  7. public function find($houseId) {
  8. $query = 'SELECT * FROM houses WHERE houseId = :houseId';
  9. $stmt = $this->pdo->prepare($query);
  10. $stmt->bindValue(':houseId', $houseId);
  11. $stmt->setFetchMode(PDO::FETCH_CLASS, 'Model\\Entities\\House');
  12. $stmt->execute();
  13. $house = $stmt->fetch(PDO::FETCH_CLASS);
  14. if (false === $house) {
  15. throw new RecordNotFoundException(
  16. 'No houses exist for the specified ID'
  17. );
  18. }
  19. return $house;
  20. }
  21. // more data mapper methods here ...
  22. }
  23. class PersonMapper {
  24. private $pdo;
  25. public function __construct(PDO $pdo) {
  26. $this->pdo = $pdo;
  27. }
  28. // data mapper methods here
  29. }
  30. class SomeService {
  31. private $houseMapper;
  32. private $personMapper;
  33. public function __construct(HouseMapper $hm, PersonMapper $pm) {
  34. $this->houseMapper = $hm;
  35. $this->personMapper = $pm;
  36. }
  37. public function doSomething() {
  38. // do something with the mappers
  39. }
  40. }

In our wiring/bootstrap code, we simply instantiate the PDO instance once and share it in the
context of the Injector:

  1. <?php
  2. $pdo = new PDO('sqlite:some_sqlite_file.db');
  3. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  4. $injector = new Amp\Injector\Injector;
  5. $injector->share($pdo);
  6. $mapper = $injector->make('SomeService');

In the above code, the DIC instantiates our service class. More importantly, the data mapper classes
it generates to do so are injected with the same database connection instance we originally shared.

Of course, we don’t have to manually instantiate our PDO instance. We could just as easily seed
the container with a definition for how to create the PDO object and let it handle things for us:

  1. <?php
  2. $injector->define('PDO', [
  3. ':dsn' => 'sqlite:some_sqlite_file.db'
  4. ]);
  5. $injector->share('PDO');
  6. $service = $injector->make('SomeService');

In the above code, the injector will pass the string definition as the $dsn argument in the
PDO::__construct method and generate the shared PDO instance automatically only if one of the
classes it instantiates requires a PDO instance!

App-Bootstrapping

DICs should be used to wire together the disparate objects of your application into a cohesive
functional unit (generally at the bootstrap or front-controller stage of the application). One such
usage provides an elegant solution for one of the thorny problems in object-oriented (OO) web
applications: how to instantiate classes in a routed environment where the dependencies are not
known ahead of time.

Consider the following front controller code whose job is to:

  1. Load a list of application routes and pass them to the router
  2. Generate a model of the client’s HTTP request
  3. Route the request instance given the application’s route list
  4. Instantiate the routed controller and invoke a method appropriate to the HTTP request
  1. <?php
  2. define('CONTROLLER_ROUTES', '/hard/path/to/routes.xml');
  3. $routeLoader = new RouteLoader();
  4. $routes = $routeLoader->loadFromXml(CONTROLLER_ROUTES);
  5. $router = new Router($routes);
  6. $requestDetector = new RequestDetector();
  7. $request = $requestDetector->detectFromSuperglobal($_SERVER);
  8. $requestUri = $request->getUri();
  9. $requestMethod = strtolower($request->getMethod());
  10. $injector = new Amp\Injector\Injector;
  11. $injector->share($request);
  12. try {
  13. if (!$controllerClass = $router->route($requestUri, $requestMethod)) {
  14. throw new NoRouteMatchException();
  15. }
  16. $controller = $injector->make($controllerClass);
  17. $callableController = array($controller, $requestMethod);
  18. if (!is_callable($callableController)) {
  19. throw new MethodNotAllowedException();
  20. } else {
  21. $callableController();
  22. }
  23. } catch (NoRouteMatchException $e) {
  24. // send 404 response
  25. } catch (MethodNotAllowedException $e) {
  26. // send 405 response
  27. } catch (Exception $e) {
  28. // send 500 response
  29. }

And elsewhere we have various controller classes, each of which ask for their own individual
dependencies:

  1. <?php
  2. class WidgetController {
  3. private $request;
  4. private $mapper;
  5. public function __construct(Request $request, WidgetDataMapper $mapper) {
  6. $this->request = $request;
  7. $this->mapper = $mapper;
  8. }
  9. public function get() {
  10. // do something for HTTP GET requests
  11. }
  12. public function post() {
  13. // do something for HTTP POST requests
  14. }
  15. }

In the above example the injector DIC allows us to write fully testable, fully OO controllers that ask
for their dependencies. Because the DIC recursively instantiates the dependencies of objects it
creates we have no need to pass around a Service Locator. Additionally, this example shows how we can
eliminate evil Singletons using the sharing capabilities of the injector DIC. In the front controller
code, we share the request object so that any classes instantiated by the Amp\Injector\Injector that ask
for a Request will receive the same instance. This feature not only helps eliminate Singletons,
but also the need for hard-to-test static properties.