PHP code example of dmt-software / di-plug

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

    

dmt-software / di-plug example snippets


use DMT\DependencyInjection\Adapters\PimpleAdapter;
use DMT\DependencyInjection\Container;
use Pimple\Container as PimpleContainer;
 
$container = new Container(new PimpleAdapter(new PimpleContainer()));
$container->set(SomeClass::class, fn() => new SomeClass($container->get(SomeDependency::class)));

use DMT\DependencyInjection\ContainerFactory;
 
/** @var object $supportedContainerInstance */
$factory = new ContainerFactory();
$container = $factory->createContainer($supportedContainerInstance);
$container->set(SomeClass::class, fn() => new SomeClass($container->get(SomeDependency::class)));

use DMT\DependencyInjection\ContainerFactory;
 
$factory = new ContainerFactory();
$container = $factory->createContainer();
$container->set(SomeClass::class, fn() => new SomeClass($container->get(SomeDependency::class)));

use DMT\DependencyInjection\Container;
use DMT\DependencyInjection\Traits\HasContainer;

class SomeClass
{
    use HasContainer;
    
    public function doSomething(): void
    {
        $dependency = $this->getContainer()->get(SomeDependency::class);
        $dependency->doSomething();
    }
}

use DMT\DependencyInjection\Traits\HasContainer;
use Twig\Environment;

trait HasTwigEngine
{
    use HasContainer;
    
    public function getTwigEngine(): Environment
    {
        return $this->getContainer()->get(Environment::class);
    }
}

use DMT\DependencyInjection\Container;
use DMT\DependencyInjection\ServiceProviderInterface;
use Twig\Environment;
use Twig\Extension\StringLoaderExtension;

class MyServiceProvider implements ServiceProviderInterface
{
    /**
     * Register dependencies and ensure twig is enabled with string loader extension.   
     */
    public function register(Container $container): void
    {
        if (!$container->has(Environment::class)) {
            $container->set(Environment::class, fn() => new Environment());
        }
        
        $env = $container->get(Environment::class);
        if (!$env->hasExtention(StringLoaderExtension::class)) {
            $env->addExtension(new StringLoaderExtension());
        }

        $container->set(MyClassInterface::class, fn() => new MyClass($container->get(Environment::class)));
    }
}