PHP code example of petk / php-container

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

    

petk / php-container example snippets




declare(strict_types=1);

use Petk\Container;

// Container instantiation.
$container = new Container();

// Adding dependencies to container is as easy as setting them to the given key.
$container->set(App\Utility::class, function ($c) {
    return new App\Utility();
});

// Adding more complex dependencies can be done like this.
$container->set(App\Database::class, function ($c) {
    return new App\Database($c->get(App\Utility::class));
});

return $container;



declare(strict_types=1);

// Require Composer autoloader.
/config/container.php';

$database = $container->get(App\Database::class);
// Use $database further.



// ...

class ChildClass
{
    public function __construct(private ParentClass $parent)
    {
    }
}

class ParentClass
{
    public function __construct(private ChildClass $child)
    {
    }
}

$container->set(ParentClass::class, function ($c) {
    return new ParentClass($c->get(ChildClass::class));
});

$container->set(ChildClass::class, function ($c) {
    return new ChildClass($c->get(ParentClass::class));
});

// This will throw ContainerCircularDependencyException.
$object = $container->get(Parent::class);