public function testSingletonWithPersistence() { $container = new Container(); $container->singleton('mySingleton', '\\stdClass'); $stdClass = $container->build('mySingleton'); $stdClass->testVar = 'value'; $stdClass2 = $container->build('mySingleton'); $this->assertEquals('value', $stdClass2->testVar); }
/** * Convert a callback expression to a valid PHP callback. * * @param string|array $id * A callback expression; any of the following. * * @return array * A PHP callback. Do not serialize (b/c it may include an object). * @throws \RuntimeException */ public function get($id) { if (!is_string($id)) { // An array or object does not need to be further resolved. return $id; } if (strpos($id, '::') !== FALSE) { // Callback: Static method. return explode('::', $id); } elseif (strpos($id, '://') !== FALSE) { $url = parse_url($id); switch ($url['scheme']) { case 'obj': // Object: Lookup in container. return Container::singleton()->get($url['host']); case 'call': // Callback: Object/method in container. $obj = Container::singleton()->get($url['host']); return array($obj, ltrim($url['path'], '/')); case 'api3': // Callback: API. return new ResolverApi($url); case 'global': // Lookup in a global variable. return new ResolverGlobalCallback($url['query'], $url['host'] . (isset($url['path']) ? rtrim($url['path'], '/') : '')); default: throw new \RuntimeException("Unsupported callback scheme: " . $url['scheme']); } } elseif (in_array($id, array('0', '1'))) { // Callback: Constant value. return new ResolverConstantCallback((int) $id); } elseif ($id[0] >= 'A' && $id[0] <= 'Z') { // Object: New/default instance. return new $id(); } else { // Callback: Function. return $id; } }
/** * Test object-lookup in the container. */ public function testObj() { // Note: ResolverTestExampleService is implemented at the bottom of this file. Container::singleton()->set('callbackTestService', new ResolverTestExampleService()); $obj = $this->resolver->get('obj://callbackTestService'); $this->assertTrue($obj instanceof ResolverTestExampleService); }
protected function registerAccessHandler() { $this->container->singleton('access', function ($app) { return $app->build(AccessHandler::class); }); }