PHP code example of dhii / services

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

    

dhii / services example snippets


new Factory(['dep1', 'dep2'], function(int $dep1, SomeInterface $dep2) {
  // ...
});

function (ContainerInterface $c) {
  $dep1 = $c->get('dep1');
  if (!is_int($dep1)) {
    throw new TypeError(sprintf('Parameter $dep1 must be of type int; %1$s given', is_object($dep1) ? get_class($dep1) : gettype($dep1));
  }

  $dep2 = $c->get('dep2');
  if (!($dep2 instanceof SomeInterface)) {
    throw new TypeError(sprintf('Parameter $dep2 must be of type int; %1$s given', is_object($dep2) ? get_class($dep2) : gettype($dep2));
  }
  // ...
}

new Extension(['dep1', 'dep2'], function($prev, $dep1, $dep2) {
  // ...
});

function (ContainerInterface $c, $prev) {
  $dep1 = $c->get('dep1');
  $dep2 = $c->get('dep2');
  // ...
}

new Constructor(MyClass::class, ['dep1', 'dep2']);

function (ContainerInterface $c) {
  $dep1 = $c->get('dep1');
  $dep2 = $c->get('dep2');

  return new MyClass($dep1, $dep2);
}

new Constructor(MyClass::class);

function (ContainerInterface $c) {
  return new MyClass();
}

new ServiceList(['service1', 'service2']);

function (ContainerInterface $c) {
  return [
    $c->get('service1'),
    $c->get('service2'),
  ];
}

new ArrayExtension(['dep1', 'dep2'])

function (ContainerInterface $c, array $prev) {
  return array_merge($prev, [
    $c->get('dep1'),
    $c->get('dep2'),
  ]);
}

new FuncService(['dep1', 'dep2'], function($arg1, $arg2, $dep1, $dep2) {
  // ...
});

function (ContainerInterface $c) {
  $dep1 = $c->get('dep1');
  $dep2 = $c->get('dep2');

  return function ($arg1, $arg2) use ($dep1, $dep2) {
    // ...
  };
}

$service = new Factory(['database'], function ($database) {
  // ...
});

$service2 = $service->withDependencies(['db']);

class LoggerProvider implements ServiceProviderInterface
{
  public function getFactories()
  {
    return [
      'logger' => new Constructor(FileLogger::class, ['file_path']),
      'file_path' => new Value(sys_get_tmp_dir() . '/log.txt')
    ];
  }
  
  public function getExtensions ()
  {
    return [];
  }
}

class PrefixingProvider implements ServiceProviderInterface {
  public function getFactories() {
    $factories = [];

    foreach ($this->provider->getFactories() as $key => $factory) {
      $deps = $factory->getDependencies();
      $newDeps = array_map(fn($dep) => $this->prefix . $dep, $deps);

      $factories[$this->prefix . $key] = $factory->withDependencies($newDeps);
    }
    
    return $factories;
  }
}

$debugLogProvider = new PrefixingProvider('debug_', new LoggerProvider);
$errorLogProvider = new PrefixingProvider('error_', new LoggerProvider);