PHP code example of pyther / ioc

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

    

pyther / ioc example snippets


use Pyther\Ioc\Ioc;

// Let's bind an implementation of “MariaDatabase” as a singleton to an interface.
// This ist afast process and will NOT trigger the autoloader.
Ioc::bindSingleton(IDatabase::class, MariaDatabase::class);

// later anywhere in your code, resolve to an instance of a MariaDatabase class
$db = Ioc::get(IDatabase::class);

Ioc::bindSingleton(ShoppingCart::class, ShoppingCart::class);

Ioc::bindMultiple(Product::class, Product::class);

class ShoppingCart
{
    function __construct(Customer $customer)
    {
        ...
    }
}

// hint: the order of binding doesn't matter.
Ioc::bindSingleton(ShippingCart::class, ShoppingCart::class);
Ioc::bindSingleton(Customer::class, Customer::class);

$cart = Ioc::get(ShoppingCart::class);

class Configurations
{
    function __construct(?string $path = null)
    {
        ...
    }
}
...
Ioc::bindSingleton(Configurations::class, Configurations::class, ["path" => "./config.json"]);

Ioc::bindSingleton(Configurations::class, function() {
    return new Configurations("./config.json);
});

Ioc::bindSingleton(Configurations::class, function(string $path) {
    return new Configurations($path);
}, ['path' => "./config.json"]);

$this->bindSingleton(IInterface::class, [AnyClass::class, "createObject"]);
// or
$this->bindSingleton(IInterface::class, "My\Namespace\AnyClass::createObject");

or with arguments

$this->bindSingleton(IInterface::class, [AnyClass::class, "createObject"], [
    "text" => "abc", "number"=> 123
]);
// or
$this->bindSingleton(IInterface::class, "My\Namespace\AnyClass::createObject", [
    "text" => "abc", "number"=> 123
]);

$this->bindSingleton(IInterface::class, [$obj, "createObject"]);
// or with arguments
$this->bindSingleton(IInterface::class, [$obj, "createObject"],  [
    "text" => "abc", "number"=> 123
]);

Ioc::bindSingleton(Configurations::class, null);

$configs = new Configurations("./config.json");
...
Ioc::bindSingleton(Configurations::class, $configs);

$exists = Ioc::has(Configurations::class);

IoC::$default->addMultiple(...)
IoC::$default->addSingleton(...)
IoC::$default->resolve(...)

$containerA = new Ioc();
$containerB = new Ioc();

$containerA->addSingleton(...);
$containerB->addMutliple(...);

$containerA->get(...);