thecodingmachine / lazy-array
此包提供了一个可以延迟实例化其包含对象的数组。
1.0.x-dev
2016-04-12 14:09 UTC
Requires
- php: >=5.6
Requires (Dev)
- phpunit/phpunit: ^4.5
- satooshi/php-coveralls: ^1.0
This package is auto-updated.
Last update: 2024-09-06 23:31:22 UTC
README
这是什么?
该项目包含一个表现得像数组的类。然而,只有当在数组中检索到键时,数组中的对象才会被实例化,因此您不必立即创建实例。这对于性能考虑非常有用。
它是如何工作的?
很简单,您创建一个新的 LazyArray
对象,然后将其中的对象推入。
$lazyArray = new LazyArray(); $key = $lazyArray->push(MyServiceProvider::class); // This will trigger the creation of the MyServiceProvider object and return it. $serviceProvider = $lazyArray[$key];
您还可以向对象的构造函数传递参数
$lazyArray = new LazyArray(); $key = $lazyArray->push(MyServiceProvider::class, "param1", "param2");
而且因为我们很友好,您还可以将已实例化的对象推入延迟数组
$lazyArray = new LazyArray(); // This is possible, even if we loose the interest of the LazyArray. $key = $lazyArray->push(new MyServiceProvider());
最后,如果您注重性能(我相信您是),您可以在一次调用中创建整个延迟数组
$lazyArray = new LazyArray([ MyServiceProvider::class, // Is you simply want to create an instance without passing parameters [ MyServiceProvider2::class, [ "param1", "param2 ] ], // Is you simply want to create an instance and pass parameters to the constructor new MyServiceProvider4('foo') // If you directly want to push the constructed instance. ]);
为什么?
正如示例所示,这是为了提高服务提供商在(编译容器环境中)加载时的性能而构建的。不要将其用作依赖注入容器的替代品,这是一个坏主意。