Example #1
0
 /**
  * Test set method
  *
  * @return void
  */
 public function testSet()
 {
     //String
     $Di = Di::instance();
     $Di->set('uuid', 'h2340sj2309');
     $actual = $Di->get('uuid');
     $expected = 'h2340sj2309';
     $this->assertSame($expected, $actual);
     //Normal
     $expected = new \stdClass();
     $expected->id = 103;
     $Di->set('service', function () {
         $job = new \stdClass();
         $job->id = 103;
         return $job;
     });
     $actual = $Di->get('service');
     $this->assertEquals($expected, $actual);
     $actual2 = $Di->get('service');
     $this->assertSame($actual2, $actual);
     //Factory
     $type = 'factory';
     $expected = new \stdClass();
     $expected->id = 150;
     $Di->set('service_2', function () {
         $job = new \stdClass();
         $job->id = 150;
         return $job;
     }, $type);
     $actual = $Di->get('service_2');
     $this->assertEquals($expected, $actual);
     $actual2 = $Di->get('service_2');
     $this->assertNotSame($actual2, $actual);
     //Parameters
     $type = 'parameter';
     $expected = function () {
         return rand();
     };
     $Di->set('random_func', $expected, $type);
     $actual = $Di->get('random_func');
     $this->assertSame($expected, $actual);
     $type = 'parameter';
     $expected = 'SESSION_ID';
     $Di->set('cookie_name', 'SESSION_ID', $type);
     $actual = $Di->get('cookie_name');
     $this->assertSame($expected, $actual);
 }
<?php

use Cake\Core\Configure;
use RochaMarcelo\CakePimpleDi\Di\Di;
$config = Configure::consume('CakePimpleDi');
$scopes = [];
if (!isset($config['scopes'])) {
    $scopes = ['default' => (array) $config];
}
foreach ($scopes as $name => $config) {
    $Di = Di::instance($name);
    $config = $config + ['providers' => []];
    foreach ($config['providers'] as $provider) {
        if (is_string($provider)) {
            $provider = new $provider();
        }
        $Di->register($provider);
    }
    if (isset($config['services']) && is_array($config['services'])) {
        $Di->setMany($config['services']);
    }
}