PHP code example of xp-forge / inject

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

    

xp-forge / inject example snippets


use inject\{Injector, Bindings};
use com\example\{Report, HtmlReport, Storage, InFileSystem};

// Manually
$injector= new Injector(Bindings::using()
  ->typed(Report::class, HtmlReport::class)
  ->singleton(Storage::class, new InFileSystem('.'))
  ->named('title', 'Report title')
);

// Reusable via Bindings instances
class ApplicationDefaults extends Bindings {

  public function configure($injector) {
    $injector->bind(Report::class, HtmlReport::class);
    $injector->bind(Storage::class, new InFileSystem('.'));
    $injector->bind('string', 'Report title', 'title');
  }
}

$injector= new Injector(new ApplicationDefaults());

use inject\Injector;

$injector->bind(Report::class, HtmlReport::class);

// Explicit binding: Lookup finds binding to HtmlReport, creates instance.
$instance= $injector->get(Report::class);

// Implicit binding: No previous binding, TextReport instantiable, thus created.
$instance= $injector->get(TextReport::class);

class ReportImpl implements Report {

  public function __construct(ReportWriter $writer) { ... }
}

use inject\Inject;

class ReportImpl implements Report {

  public function __construct(
    ReportWriter $writer,
    Format $format,
    #[Inject(type: 'string[]', name: 'report-titles')]
    $titles
  ) { ... }
}

class ReportWriter implements Writer {

  public function __construct(Storage $storage) { ... }
}

$injector= new Injector();
$report= $injector->get(ReportWriter::class);  // *** Storage not bound

$injector= new Injector(
  new ApplicationDefaults(),
  new ConfiguredBindings(new Properties('etc/app.ini'))
);

$provider= $injector->get('inject.Provider<com.example.writers.ReportWriter>');

// ...later on
$instance= $provider->get();

use inject\{Injector, Named, InstanceBinding};
use com\example\Value;

$inject= new Injector();
$inject->bind(Value::class, new class() extends Named {
  public function provides($name) { return true; }
  public function binding($name) { return new InstanceBinding(new Value($name)); }
});

$value= $inject->get(Value::class, 'default');  // new Value("default")