The implementation of a dependency injection on PHP

v1.1.0 2019-07-01 04:45 UTC

This package is auto-updated.

Last update: 2024-10-29 05:52:55 UTC


README

Build Status Coverage Status

Usage:

<?php

use \Acme\Services\MyService1;
use \Acme\Services\MyService2;
use \Acme\Services\MyService2Factory;
use \Acme\Services\MyService3;
use \AwdStudio\DI\Storage\Registry;
use \AwdStudio\DI\ContainerFactory;

// Create a new registry
$registry = new Registry();

// Builds the container
$container = ContainerFactory::build($registry);

// Minimum service registration
$registry->register(MyService1::class);

// Named service
$registry->register('my.second.service')
         ->class(MyService2::class)
         ->factory(MyService2Factory::class, 'build', []);

// Add tagged services
$service = MyService1::class;
$serviceWeight = 25; // Set up service weight for custom sorting
$registry->register($service);
$registry->tag('my.tag', $service, $serviceWeight);


// Service with arguments
$registry->register('my.service')
         ->class(MyService2::class) // Service interface or class
         ->arguments([              // Arguments for the construct the service
             'Simple Argument',     // Raw parameter
             '\!skip',              // Argument to skip
             '@my.second.service',  // Another named service
         ]);

// Check service existing
$container->has('@my.second.service');

// Fetch a service
$container->get('@my.second.service');
$container->get(MyService2::class);

// Factory method
$registry->register(MyService1::class)
         ->factory(MyStatic::class, 'factoryMethodName', [
             'Simple Argument', 
             '@my.second.service'
         ]);

// Static factory method
$registry->register(MyService1::class)
         ->fromCallable([MyStatic::class, 'build']);
//         ->fromCallable(['\Full\Namespace\MyStatic', 'build']);

// Common function
$registry->register(MyService1::class)
         ->fromCallable('callableFunction');
         
// Closure factory
$registry->register(MyService1::class)
         ->fromCallable(function ($arg) {
             return new MyService1($arg);
         })
         ->arguments(['My argument']);

Testing:

composer test