PHP code example of esase / tiny-service-manager

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

    

esase / tiny-service-manager example snippets





class A {
    private B $embedded;

    public function __construct() {
        // Issues:
        // 1. we cannot test it because we cannot mimic it
        // 2. If we decide to use another implementation we will have to find and replace all its references
        $this->embedded = new B();
    }
}





class A {
    private B $embedded;

    public function __construct(B $embedded) {
        $this->embedded = $embedded;
    }
}


    use Tiny\ServiceManager\ServiceManager;

    // The Service Manager is a service/object locator, tasked with retrieving other objects.
    $serviceManager = new ServiceManager([
        B::class => function(ServiceManager $serviceManager) {
            return new B();
        },
        A::class => function(ServiceManager $serviceManager) {
            return new A($serviceManager->get(B::class));
        }
    ]);

    // now whenever we get an instance of "A" class we get it with injected instance of "B" class
    $serviceA = $serviceManager->get(A::class);


$serviceA = new A(new MockedB());