PHP code example of jitesoft / container

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

    

jitesoft / container example snippets


interface ContainerInterface {
  public function get($abstract): mixed;
  public function has($abstract): bool;
}

interface ArrayAccess {
  public function offsetExists($offset);
  public function offsetGet($offset);
  public function offsetSet($offset, $value);
  public function offsetUnset($offset);
}

$c['Abstract'] = 'Concrete';
echo $c['Abstract']; // 'Concrete'
unset($c['Abstract'];

class Container {
  public function __construct(?array $bindings);
  public function clear();
  public function set(string $abstract, mixed $concrete, ?bool $singleton = false): bool;
  public function rebind(string $abstract, mixed $concrete, ?bool $singleton = false): void;
  public function unset(string $abstract): void;
  
  public function singleton(string $abstract, mixed $concrete): void;
}

$container = new Container([

  // With objects:
  InterfaceA::class => $objectInheritingInterfaceA,
  InterfaceB::class => [
    'class' => $objectInheritingInterfaceB,
    'singleton' => true
  ],

  // With classes:
  InterfaceA::class => ClassA::class,
  InterfaceB::class => [
    'class' => ClassB::class,
    'singleton' => true
  ],

  // Or with functions:
  InterfaceA::class => static fn (InterfaceB $ib) => new ClassA($ib),
  InterfaceB::class => [
    'class' => static function(InterfaceC $c) {
      return new ClassB($c);
    },
    'singleton' => true
  ],

]);

$container->get(InterfaceA::class); // Will be a new object of the ClassA class.
$container->get(InterfaceB::class); // On first call, it will be resolved to a ClassB class.
$container->get(InterfaceB::class); // On all other calls, the object will be the same as the first call.

class ClassA {}

class ClassB {
  __constructor(ClassA $b) { }
}

$container->set(ClassB::class, ClassB::class);
$container->get(ClassB::class); // Will throw a ContainerException due to class A not being bound.

$container->set(ClassA::class, ClassA::class);
$container->get(ClassB::class); // Will not throw any exception. ClassA is resolved and pushed into the constructor of ClassB.

$container->set('Something', 123);
$container->get('Something'); // 123