PHP code example of semperton / container

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

    

semperton / container example snippets


new Container(iterable $definitions = [])

withAutowiring(bool $flag): Container // toggle autowiring
withEntry(string $id, mixed $entry): Container // add a container entry
withDelegate(ContainerInterface $delegate): Container // register a delegate container
get(string $id): mixed // get entry (PSR-11)
has(string $id): bool // has entry (PSR-11)
create(string $id, array $params = []): mixed // create a class with optional constructor substitution args
entries(): array // list all container entries

use Semperton\Container\Container;

class World
{
	public function __toString()
	{
		return 'World';
	}
}

class Hello
{
	protected $world;
	public function __construct(World $world)
	{
		$this->world = $world;
	}
	public function print()
	{
		echo "Hello {$this->world}";
	}
}

$container = new Container();
$hello = $container->get(Hello::class);
$hello2 = $container->get(Hello::class);

$hello instanceof Hello::class // true
$hello === $hello2 // true
$hello->print(); // 'Hello World'

use Semperton\Container\Container;

class Mail
{
	public function __construct(Config $c, string $to)
	{
	}
}

class MailFactory
{
	public function createMail(string $to)
	{
		return new Mail(new Config(), $to);
	}
}

$mail1 = $container->get(MailFactory::class)->createMail('[email protected]');
$mail2 = $container->create(Mail::class, ['to' =>'[email protected]']);


use Semperton\Container\Container;

$container = new Container([

	'mail' => '[email protected]',
	'closure' => static function () { // closures must be wrapped in another closure
		return static function () {
			return 42;
		};
	},
	MailFactory::class => new MailFactory('[email protected]'), // avoid this, instead do
	MailFactory::class => static function (Container $c) { // lazy instantiation with a factory

		$sender = $c->get('mail');
		return new MailFactory($sender);
	}, // or
	// factory params are automatically resolved from the container
	MailFactory::class => static fn (string $mail) => new MailFactory($mail),
	Service::class => static fn (Dependency $dep) => new Service($dep)
]);

$container->get('mail'); // '[email protected]'
$container->get('closure')(); // 42
$container->get(MailFactory::class); // instance of MailFactory

use Semperton\Container\Container;

$container1 = new Container();
$container2 = $container1->withEntry('number', 42);

$container1->has('number'); // false
$container2->has('number'); // true

$container1 === $container2 // false