Skip to content

Instantly share code, notes, and snippets.

@jeffturcotte
Last active August 29, 2015 13:57
Show Gist options
  • Save jeffturcotte/9557854 to your computer and use it in GitHub Desktop.
Save jeffturcotte/9557854 to your computer and use it in GitHub Desktop.
Injector register method
<?php
/**
* Register a dependency. The following formats are allowed:
*
* 1. Fully qualified class (or interface) name with factory closure:
* $injector->register('Fully\Qualified\ClassName', function { .... });
*
* 2. Fully qualified class (or interface) name with instance of said class:
* $injector->register('Fully\Qualified\ClassName', $instance);
*
* 3. Fully qualified class (or interface) name with factory Callable:
* $injector->register('Fully\Qualified\ClassName', [$instance, 'factoryMethod']);
*
* 4. Fully qualified class name only. Will inject dependencies into the constructor
* $injector->register('Fully\Qualified\ClassName');
*
* 5. Fully qualified interface name with fully qualified class name:
* $injector->register('Fuilly\Qualified\InterfaceName', 'Fully\Qualified\ClassName');
*
* 6. Instance only:
* $injector->register($instance);
*
* @param mixed $type
* A fully qualified class name, interface name, or object
*
* @param mixed $implementation
* A Closure factory, Callable factory, instance, or fully qualified class name
*
* @return iMarc\Zap\Injector
* The injector instance
*/
public function register($type, $implementation = null)
{
if ($implementation instanceof Closure) {
$this->factories[$type] = $implementation;
} else if (is_object($implementation)) {
$this->instances[$type] = $implementation;
} else if (is_callable($implementation) {
$this->factories[$type] = $implementation;
} else if ($implementation === null && is_string($type)) {
$this->factories[$type] = $this->createFactory($type);
} else if (is_string($type) && is_string($implementation)) {
$this->factories[$type] = $this->createFactory($implementation);
} else if ($implementation === null && is_object($type)) {
$this->instance[get_class($type)] = $type;
} else {
throw new InvalidArgumentException("Invalid dependency registration");
}
return $this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment