depend/depend

Lazy Dependency Injection for cross framework libraries.

1.0.4 2019-09-23 08:32 UTC

This package is not auto-updated.

Last update: 2024-04-30 06:04:15 UTC


README

Depend provides namespace scoped, lazy loading dependency injection, so that you can use dependency injection within your library, even if the hosting application don't support dependency injection.

It works with any PSR-11 compatible container, such as those provided by frameworks like Symfony, Zend and Laravel. See Container Implementation.

Namespaced

Depend can be configured on a per namespace basis:

<?php
use Depend\Depend;

/**
 * The root namespace should be configured to use the applications
 * default container.
 */
Depend::registerContainer( '', $container );

/**
 * Want Guzzle to use a different container?
 */
Depend::registerContainer( 'GuzzleHttp', $differentContainer );
?>

What happens? Depend creates a global autoloader that will look for the special namespace 'service' (all lowercase) in part of the requested class namespace. So if you require "service\GuzzleHttp\ClientInterface" in your library that uses the "YourLibrary" namespace, then the dependency will be resolved as YourLibrary**service**\GuzzleHttp\ClientInterface

Developers are responsible for declaring which container should be used.

If a container not been declared for a namespace, Depend will check the parent namespace until it reaches the top namespace.

For libraries

If you are developing a library, and you wish to use Depend-style dependency injection, you should provide a container for your library:

<?php
namespace MyExampleLibrary;

use Depend\Depend;

Depend::registerContainer ( __NAMESPACE__, $yourContainer );
?>

Auto-wiring

There is no magic, just PHP traits:

<?php
namespace App\Controllers;

class Website {

    use service\Psr\Log\LoggerInterface [
        LoggerInterface as log;
    }
    use service\PDO {
        PDO as db;
    }

    public function homepage() {
        $this->log()->debug('Homepage was requested');
        
        return $this->view('homepage');
    }
}

What happens? Whenever a package tries to import a dependency, Depend will automatically generate a trait that will be loaded by the autoloader. This trait has a method that calls the registered container.