PHP code example of caridea / container

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

    

caridea / container example snippets


$config = [
    'db.uri' => 'mongodb://localhost:27017',
    'mail.host' => '192.168.1.100'
];
$properties = new \Caridea\Container\Properties($config);
$objects = \Caridea\Container\Objects::builder()
    ->eager('mongoClient', 'MongoClient', function($c){
        return new \MongoClient($c->get('db.uri'));
    })
    ->lazy('mailService', 'My\Mail\Service', function($c){
        return new \My\Mail\Service($c->('mail.host'));
    })
    ->lazy('userService', 'My\User\Service', function($c){
        return new \My\User\Service($c->get('mongoClient'), $c->get('objectStorage'));
    })
    ->proto('objectStorage', 'SplObjectStorage', function($c){
        return new \SplObjectStorage();
    })
    ->build($properties);

$userService = $objects->get('userService');

$services = \Caridea\Container\Objects::builder()
    ->eager('blogService', 'My\Blog\Service', function($c){
        return new \My\Blog\Service();
    })
    ->build();
$controllers = \Caridea\Container\Objects::builder()
    ->eager('blogController', 'My\Blog\Controller', function($c){
        return new \My\Blog\Controller($c->get('blogService'));
    })
    ->build($services);

$controllers = $controllers->getByType('My\Blog\Controller'); // ['blogController' => BlogController]

$objects = \Caridea\Container\Objects::builder()
    ->eager('eventListener', 'My\Cool\EventListener', function($c){
        // we are assuming that this class implements Caridea\Event\Listener
        return new \My\Cool\EventListener();
    })
    ->build();

// assuming that CustomEvent implements Caridea\Event\Event
$objects->publish(new CustomEvent());
// Here, the eventListener object will have its ->notify() method invoked with the CustomEvent

class MyContainerAware implements \Caridea\Container\ContainerAware
{
    use \Caridea\Container\ContainerSetter;

    public function __construct()
    {
        $this->container = new \Caridea\Container\EmptyContainer();
    }
}