当前位置: 首页 > 文档资料 > Laravel 源码详解 >

Laravel Ioc 容器 - Laravel Container——服务容器的细节特性

优质
小牛编辑
137浏览
2023-12-01

在前面几个博客中,我详细讲了 Ioc 容器各个功能的使用、绑定的源码、解析的源码,今天这篇博客会详细介绍 Ioc 容器的一些细节,一些特性,以便更好地掌握容器的功能。

注:本文使用的测试类与测试对象都取自 laravel 的单元测试文件src/illuminate/tests/Container/ContainerTest.php

rebind绑定特性

rebind 在绑定之前

instance 和 普通 bind 绑定一样,当重新绑定的时候都会调用 rebind 回调函数,但是有趣的是,对于普通 bind 绑定来说,rebind 回调函数被调用的条件是当前接口被解析过:

  1. public function testReboundListeners()
  2. {
  3. unset($_SERVER['__test.rebind']);
  4. $container = new Container;
  5. $container->rebinding('foo', function () {
  6. $_SERVER['__test.rebind'] = true;
  7. });
  8. $container->bind('foo', function () {
  9. });
  10. $container->make('foo');
  11. $container->bind('foo', function () {
  12. });
  13. $this->assertTrue($_SERVER['__test.rebind']);
  14. }

所以遇到下面这样的情况,rebinding 的回调函数是不会调用的:

  1. public function testReboundListeners()
  2. {
  3. unset($_SERVER['__test.rebind']);
  4. $container = new Container;
  5. $container->rebinding('foo', function () {
  6. $_SERVER['__test.rebind'] = true;
  7. });
  8. $container->bind('foo', function () {
  9. });
  10. $container->bind('foo', function () {
  11. });
  12. $this->assertFalse(isset($_SERVER['__test.rebind']));
  13. }

有趣的是对于 instance 绑定:

  1. public function testReboundListeners()
  2. {
  3. unset($_SERVER['__test.rebind']);
  4. $container = new Container;
  5. $container->rebinding('foo', function () {
  6. $_SERVER['__test.rebind'] = true;
  7. });
  8. $container->bind('foo', function () {
  9. });
  10. $container->instance('foo', function () {
  11. });
  12. $this->assertTrue(isset($_SERVER['__test.rebind']));
  13. }

rebinding 回调函数却是可以被调用的。其实原因就是 instance 源码中 rebinding 回调函数调用的条件是 rebound 为真,而普通 bind 函数调用 rebinding 回调函数的条件是 resolved 为真. 目前笔者不是很清楚为什么要对 instance 和 bind 区别对待,希望有大牛指导。

rebind 在绑定之后

为了使得 rebind 回调函数在下一次的绑定中被激活,在 rebind 函数的源码中,如果判断当前对象已经绑定过,那么将会立即解析:

  1. public function rebinding($abstract, Closure $callback)
  2. {
  3. $this->reboundCallbacks[$abstract = $this->getAlias($abstract)][] = $callback;
  4. if ($this->bound($abstract)) {
  5. return $this->make($abstract);
  6. }
  7. }

单元测试代码:

  1. public function testReboundListeners1()
  2. {
  3. unset($_SERVER['__test.rebind']);
  4. $container = new Container;
  5. $container->bind('foo', function () {
  6. return 'foo';
  7. });
  8. $container->resolving('foo', function () {
  9. $_SERVER['__test.rebind'] = true;
  10. });
  11. $container->rebinding('foo', function ($container,$object) {//会立即解析
  12. $container['foobar'] = $object.'bar';
  13. });
  14. $this->assertTrue($_SERVER['__test.rebind']);
  15. $container->bind('foo', function () {
  16. });
  17. $this->assertEquals('bar', $container['foobar']);
  18. }

resolving 特性

resolving 回调的类型

resolving 不仅可以针对接口执行回调函数,还可以针对接口实现的类型进行回调函数。

  1. public function testResolvingCallbacksAreCalledForType()
  2. {
  3. $container = new Container;
  4. $container->resolving('StdClass', function ($object) {
  5. return $object->name = 'taylor';
  6. });
  7. $container->bind('foo', function () {
  8. return new StdClass;
  9. });
  10. $instance = $container->make('foo');
  11. $this->assertEquals('taylor', $instance->name);
  12. }
  13. public function testResolvingCallbacksShouldBeFiredWhenCalledWithAliases()
  14. {
  15. $container = new Container;
  16. $container->alias('StdClass', 'std');
  17. $container->resolving('std', function ($object) {
  18. return $object->name = 'taylor';
  19. });
  20. $container->bind('foo', function () {
  21. return new StdClass;
  22. });
  23. $instance = $container->make('foo');
  24. $this->assertEquals('taylor', $instance->name);
  25. }

resolving 回调与 instance

前面讲过,对于 singleton 绑定来说,resolving 回调函数仅仅运行一次,只在 singleton 第一次解析的时候才会调用。如果我们利用 instance 直接绑定类的对象,不需要解析,那么 resolving 回调函数将不会被调用:

  1. public function testResolvingCallbacksAreCalledForSpecificAbstracts()
  2. {
  3. $container = new Container;
  4. $container->resolving('foo', function ($object) {
  5. return $object->name = 'taylor';
  6. });
  7. $obj = new StdClass;
  8. $container->instance('foo', $obj);
  9. $instance = $container->make('foo');
  10. $this->assertFalse(isset($instance->name));
  11. }

extend 扩展特性

extend 用于扩展绑定对象的功能,对于普通绑定来说,这个函数的位置很灵活:

在绑定前扩展

  1. public function testExtendIsLazyInitialized()
  2. {
  3. ContainerLazyExtendStub::$initialized = false;
  4. $container = new Container;
  5. $container->extend('IlluminateTestsContainerContainerLazyExtendStub', function ($obj, $container) {
  6. $obj->init();
  7. return $obj;
  8. });
  9. $container->bind('IlluminateTestsContainerContainerLazyExtendStub');
  10. $this->assertFalse(ContainerLazyExtendStub::$initialized);
  11. $container->make('IlluminateTestsContainerContainerLazyExtendStub');
  12. $this->assertTrue(ContainerLazyExtendStub::$initialized);
  13. }

在绑定后解析前扩展

  1. public function testExtendIsLazyInitialized()
  2. {
  3. ContainerLazyExtendStub::$initialized = false;
  4. $container = new Container;
  5. $container->bind('IlluminateTestsContainerContainerLazyExtendStub');
  6. $container->extend('IlluminateTestsContainerContainerLazyExtendStub', function ($obj, $container) {
  7. $obj->init();
  8. return $obj;
  9. });
  10. $this->assertFalse(ContainerLazyExtendStub::$initialized);
  11. $container->make('IlluminateTestsContainerContainerLazyExtendStub');
  12. $this->assertTrue(ContainerLazyExtendStub::$initialized);
  13. }

在解析后扩展

  1. public function testExtendIsLazyInitialized()
  2. {
  3. ContainerLazyExtendStub::$initialized = false;
  4. $container = new Container;
  5. $container->bind('IlluminateTestsContainerContainerLazyExtendStub');
  6. $container->make('IlluminateTestsContainerContainerLazyExtendStub');
  7. $this->assertFalse(ContainerLazyExtendStub::$initialized);
  8. $container->extend('IlluminateTestsContainerContainerLazyExtendStub', function ($obj, $container) {
  9. $obj->init();
  10. return $obj;
  11. });
  12. $this->assertFalse(ContainerLazyExtendStub::$initialized);
  13. $container->make('IlluminateTestsContainerContainerLazyExtendStub');
  14. $this->assertTrue(ContainerLazyExtendStub::$initialized);
  15. }

可以看出,无论在哪个位置,extend 扩展都有 lazy 初始化的特点,也就是使用 extend 函数并不会立即起作用,而是要等到 make 解析才会激活。

extend 与 instance 绑定

对于 instance 绑定来说,暂时 extend 的位置需要位于 instance 之后才会起作用,并且会立即起作用,没有 lazy 的特点:

  1. public function testExtendInstancesArePreserved()
  2. {
  3. $container = new Container;
  4. $obj = new StdClass;
  5. $obj->foo = 'foo';
  6. $container->instance('foo', $obj);
  7. $container->extend('foo', function ($obj, $container) {
  8. $obj->bar = 'baz';
  9. return $obj;
  10. });
  11. $this->assertEquals('foo', $container->make('foo')->foo);
  12. $this->assertEquals('baz', $container->make('foo')->bar);
  13. }

extend 绑定与 rebind 回调

无论扩展对象是 instance 绑定还是 bind 绑定,extend 都会启动 rebind 回调函数:

  1. public function testExtendReBindingInstance()
  2. {
  3. $_SERVER['_test_rebind'] = false;
  4. $container = new Container;
  5. $container->rebinding('foo',function (){
  6. $_SERVER['_test_rebind'] = true;
  7. });
  8. $obj = new StdClass;
  9. $container->instance('foo',$obj);
  10. $container->make('foo');
  11. $container->extend('foo', function ($obj, $container) {
  12. return $obj;
  13. });
  14. this->assertTrue($_SERVER['_test_rebind']);
  15. }
  16. public function testExtendReBinding()
  17. {
  18. $_SERVER['_test_rebind'] = false;
  19. $container = new Container;
  20. $container->rebinding('foo',function (){
  21. $_SERVER['_test_rebind'] = true;
  22. });
  23. $container->bind('foo',function (){
  24. $obj = new StdClass;
  25. return $obj;
  26. });
  27. $container->make('foo');
  28. $container->extend('foo', function ($obj, $container) {
  29. return $obj;
  30. });
  31. this->assertFalse($_SERVER['_test_rebind']);
  32. }

contextual 绑定特性

contextual 在绑定前

contextual 绑定不仅可以与 bind 绑定合作,相互不干扰,还可以与 instance 绑定相互合作。而且 instance 的位置也很灵活,可以在 contextual 绑定前,也可以在contextual 绑定后:

  1. public function testContextualBindingWorksForExistingInstancedBindings()
  2. {
  3. $container = new Container;
  4. $container->instance('IlluminateTestsContainerIContainerContractStub', new ContainerImplementationStub);
  5. $container->when('IlluminateTestsContainerContainerTestContextInjectOne')->needs('IlluminateTestsContainerIContainerContractStub')->give('IlluminateTestsContainerContainerImplementationStubTwo');
  6. $this->assertInstanceOf(
  7. 'IlluminateTestsContainerContainerImplementationStubTwo',
  8. $container->make('IlluminateTestsContainerContainerTestContextInjectOne')->impl
  9. );
  10. }

contextual 在绑定后

  1. public function testContextualBindingWorksForNewlyInstancedBindings()
  2. {
  3. $container = new Container;
  4. $container->when('IlluminateTestsContainerContainerTestContextInjectOne')->needs('IlluminateTestsContainerIContainerContractStub')->give('IlluminateTestsContainerContainerImplementationStubTwo');
  5. $container->instance('IlluminateTestsContainerIContainerContractStub', new ContainerImplementationStub);
  6. $this->assertInstanceOf(
  7. 'IlluminateTestsContainerContainerImplementationStubTwo',
  8. $container->make('IlluminateTestsContainerContainerTestContextInjectOne')->impl
  9. );
  10. }

contextual 绑定与别名

contextual 绑定也可以在别名上进行,无论赋予别名的位置是 contextual 的前面还是后面:

  1. public function testContextualBindingDoesntOverrideNonContextualResolution()
  2. {
  3. $container = new Container;
  4. $container->instance('stub', new ContainerImplementationStub);
  5. $container->alias('stub', 'IlluminateTestsContainerIContainerContractStub');
  6. $container->when('IlluminateTestsContainerContainerTestContextInjectTwo')->needs('IlluminateTestsContainerIContainerContractStub')->give('IlluminateTestsContainerContainerImplementationStubTwo');
  7. $this->assertInstanceOf(
  8. 'IlluminateTestsContainerContainerImplementationStubTwo',
  9. $container->make('IlluminateTestsContainerContainerTestContextInjectTwo')->impl
  10. );
  11. $this->assertInstanceOf(
  12. 'IlluminateTestsContainerContainerImplementationStub',
  13. $container->make('IlluminateTestsContainerContainerTestContextInjectOne')->impl
  14. );
  15. }
  16. public function testContextualBindingWorksOnNewAliasedBindings()
  17. {
  18. $container = new Container;
  19. $container->when('IlluminateTestsContainerContainerTestContextInjectOne')->needs('IlluminateTestsContainerIContainerContractStub')->give('IlluminateTestsContainerContainerImplementationStubTwo');
  20. $container->bind('stub', ContainerImplementationStub::class);
  21. $container->alias('stub', 'IlluminateTestsContainerIContainerContractStub');
  22. $this->assertInstanceOf(
  23. 'IlluminateTestsContainerContainerImplementationStubTwo',
  24. $container->make('IlluminateTestsContainerContainerTestContextInjectOne')->impl
  25. );
  26. }

争议

目前比较有争议的是下面的情况:

  1. public function testContextualBindingWorksOnExistingAliasedInstances()
  2. {
  3. $container = new Container;
  4. $container->alias('IlluminateTestsContainerIContainerContractStub', 'stub');
  5. $container->instance('stub', new ContainerImplementationStub);
  6. $container->when('IlluminateTestsContainerContainerTestContextInjectOne')->needs('stub')->give('IlluminateTestsContainerContainerImplementationStubTwo');
  7. $this->assertInstanceOf(
  8. 'IlluminateTestsContainerContainerImplementationStubTwo',
  9. $container->make('IlluminateTestsContainerContainerTestContextInjectOne')->impl
  10. );
  11. }

由于instance的特性,当别名被绑定到其他对象上时,别名 stub 已经失去了与 IlluminateTestsContainerIContainerContractStub 之间的关系,因此不能使用 stub 代替作上下文绑定。
但是另一方面:

  1. public function testContextualBindingWorksOnBoundAlias()
  2. {
  3. $container = new Container;
  4. $container->alias('IlluminateTestsContainerIContainerContractStub', 'stub');
  5. $container->bind('stub', ContainerImplementationStub::class);
  6. $container->when('IlluminateTestsContainerContainerTestContextInjectOne')->needs('stub')->give('IlluminateTestsContainerContainerImplementationStubTwo');
  7. $this->assertInstanceOf(
  8. 'IlluminateTestsContainerContainerImplementationStubTwo',
  9. $container->make('IlluminateTestsContainerContainerTestContextInjectOne')->impl
  10. );
  11. }

代码只是从 instance 绑定改为 bind 绑定,由于 bind 绑定只切断了别名中的 alias 数组的联系,并没有断绝abstractAlias数组的联系,因此这段代码却可以通过,很让人难以理解。本人在给 Taylor Otwell 提出 PR 时,作者原话为“I’m not making any of these changes to the container on a patch release.”。也许,在以后(5.5或以后)版本作者会更新这里的逻辑,我们就可以看看服务容器对别名绑定的态度了,大家也最好不要这样用。

服务容器中的闭包函数参数

服务容器中很多函数都有闭包函数,这些闭包函数可以放入特定的参数,在绑定或者解析过程中,这些参数会被服务容器自动带入各种类对象或者服务容器实例。

bind 闭包参数

  1. public function testAliasesWithArrayOfParameters()
  2. {
  3. $container = new Container;
  4. $container->bind('foo', function ($app, $config) {
  5. return $config;
  6. });
  7. $container->alias('foo', 'baz');
  8. $this->assertEquals([1, 2, 3], $container->makeWith('baz', [1, 2, 3]));
  9. }

extend 闭包参数

  1. public function testExtendedBindings()
  2. {
  3. $container = new Container;
  4. $container['foo'] = 'foo’;
  5. $container->extend('foo', function ($old, $container) {
  6. return $old.'bar’;
  7. });
  8. $this->assertEquals('foobar', $container->make('foo'));
  9. $container = new Container;
  10. $container->singleton('foo', function () {
  11. return (object) ['name' => 'taylor'];
  12. });
  13. $container->extend('foo', function ($old, $container) {
  14. $old->age = 26;
  15. return $old;
  16. });
  17. $result = $container->make('foo');
  18. $this->assertEquals('taylor', $result->name);
  19. $this->assertEquals(26, $result->age);
  20. $this->assertSame($result, $container->make('foo'));
  21. }

bindmethod 闭包参数

  1. public function testCallWithBoundMethod()
  2. {
  3. $container = new Container;
  4. $container->bindMethod('IlluminateTestsContainerContainerTestCallStub@unresolvable', function ($stub,$container) {
  5. $container['foo'] = 'foo';
  6. return $stub->unresolvable('foo', 'bar');
  7. });
  8. $result = $container->call('IlluminateTestsContainerContainerTestCallStub@unresolvable');
  9. $this->assertEquals(['foo', 'bar'], $result);
  10. $this->assertEquals('foo',$container['foo']);
  11. }

resolve 闭包参数

  1. public function testResolvingCallbacksAreCalledForSpecificAbstracts()
  2. {
  3. $container = new Container;
  4. $container->resolving('foo', function ($object,$container) {
  5. return $object->name = 'taylor';
  6. });
  7. $container->bind('foo', function () {
  8. return new StdClass;
  9. });
  10. $instance = $container->make('foo');
  11. $this->assertEquals('taylor', $instance->name);
  12. }

rebinding 闭包参数

  1. public function testReboundListeners()
  2. {
  3. $container = new Container;
  4. $container->bind('foo', function () {
  5. return 'foo';
  6. });
  7. $container->rebinding('foo', function ($container,$object) {
  8. $container['bar'] = $object.'bar';
  9. });
  10. $container->bind('foo', function () {
  11. });
  12. $this->assertEquals('bar',$container['foobar']);
  13. }