PHP code example of awd-studio / di

1. Go to this page and download the library: Download awd-studio/di library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

awd-studio / di example snippets




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']);