PHP code example of renakdup / simple-dic

1. Go to this page and download the library: Download renakdup/simple-dic 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/ */

    

renakdup / simple-dic example snippets


use Renakdup\SimpleDIC\Container;

// create container
$container = new Container();

// set service
$container->set( Paypal::class, function () {
    return new Paypal();
} );

// get service
$paypal = $container->get( Paypal::class );

// use this object
$paypal->pay();

$container->set( 'requests_limit', 100 );
$container->set( 'post_type', 'products' );
$container->set( 'users_ids', [ 1, 2, 3, 4] );

$user_ids = $container->get( 'users_ids', [ 1, 2, 3, 4] );

$obj1 = $constructor->get( Paypal::class );
$obj2 = $constructor->get( Paypal::class );
var_dump( $obj1 === $obj2 ) // true

$container->set( Paypal::class, function () {
    return new Paypal();
} );

$container->set( Paypal::class, function () {
    return new Paypal();
} );

$paypal = $constructor->get( Paypal::class ); // PayPal instance created

$container->set( 'config', [
    'currency' => '$',
    'environment' => 'production',
] );

$container->set( Paypal::class, function ( Container $c ) {
    return new Paypal( $c->get('config') );
} );

class PayPalSDK {}
class Logger {}

class Paypal {
    public function __constructor( PayPalSDK $pal_sdk, Logger $logger ) {
        //...
    }
}

new Paypal( new PayPalSDK(), new Logger() );

class Logger {
    public function __constructor( $type = 'filestorage', $error_lvl = 1 ) {
        //...
    }
}

$conatainer->make( Paypal::class );

class PayPalSDK {}

class Paypal {
    public PayPalSDK $pal_sdk;
    public function __constructor( PayPalSDK $pal_sdk ) {
        $this->pal_sdk = $pal_sdk;
    }
}

// if we create PayPal instances twice
$paypal1 = $container->make( Paypal::class );
$paypal2 = $container->make( Paypal::class );

var_dump( $paypal1 !== $paypal2 ); // true
var_dump( $paypal1->pal_sdk === $paypal2->pal_sdk ); // true
bash
composer