PHP code example of coroq / container

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

    

coroq / container example snippets


use Coroq\Container\Container;
use function Coroq\Container\factory;
use function Coroq\Container\singleton;

// Create a container.
$container = new Container();

// Register some entries.

// A regular value.
$container->set('config', ['site_name' => 'Container Example']);

// Singleton: Only one instance of MyService is created and reused.
$container->set('myService', singleton(function($config) {
  // singleton() provides arguments from container entries that match the parameter name.
  // So, $config is retrieved from $container->get('config').
  $myService = new MyService();
  $myService->setSiteName($config['site_name']);
  return $myService;
}));

// Factory: A new instance of MyEntity is created every time it's requested.
$container->set('myEntity', factory(function(MyService $myService) {
  // You can use type hints for the arguments.
  // Note that arguments are bound by their names, not their types.
  return new MyEntity($myService);
}));

// Get a new instance of MyEntity from the container.
$myEntity = $container->get('myEntity');

// With the setMany() method, you can quickly add multiple entries to the container.
$container->setMany([
  'entry1' => 'value1',
  'entry2' => 'value2',
]);

// This is the same as doing:
$container->set('entry1', 'value1');
$container->set('entry2', 'value2');

use function Coroq\Container\alias;

$container->setMany([
  'psr17Factory' => singleton(function() {
    return new Psr17Factory();
  }),
  'requestFactory' => alias('psr17Factory'),
  'responseFactory' => alias('psr17Factory'),
  'uriFactory' => alias('psr17Factory'),
]);

$requestFactory = $container->get('requestFactory');
// $requestFactory === $container->get('psr17Factory').