PHP code example of slidesworker / servicelocator

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

    

slidesworker / servicelocator example snippets


namespace Example;

use SlidesWorker\ServiceLocator\ServiceLocator;

class Service1
{
}
class Service2
{
}

// setup ServiceLocator
$serviceLocator = new ServiceLocator();

$serviceLocator->set('service1', new Service1());
$serviceLocator->set('service2', new Service2());

$service1 = $serviceLocator->get('service1');
$service2 = $serviceLocator->get('service2');

namespace Example;

use SlidesWorker\ServiceLocator\ServiceLocator;
use SlidesWorker\ServiceLocator\ServiceLocatorInterface;

class Service {}

// setup ServiceLocator
$serviceLocator = new ServiceLocator();


// factory as closure
$serviceLocator->setFactory('service', function (ServiceLocatorInterface $locator) {
    return Service();
});

// get a service
$service = $serviceLocator->get('service');

namespace Example;

use SlidesWorker\ServiceLocator\ServiceLocator;
use SlidesWorker\ServiceLocator\ServiceLocatorInterface;
use SlidesWorker\ServiceLocator\ServiceLocatorAwareInterface;
use SlidesWorker\ServiceLocator\ServiceLocatorAwareTrait;

// only php 5.4 and higher
class ServiceCanHoldServiceLocator1
{
    use ServiceLocatorAwareTrait;
}


// setup ServiceLocator
$serviceLocator = new ServiceLocator();

// factory as closure
$serviceLocator->setFactory('service', function (ServiceLocatorInterface $locator) {
    return new ServiceCanHoldServiceLocator1();
});

$serviceLocator->get('service');