laravelba / proxyvel
laravel 的 IoC 容器服务代理
Requires
- illuminate/container: ~4.2
- ocramius/proxy-manager: ~1.0
Requires (Dev)
- laravel/framework: ~4.2
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2022-02-01 12:44:46 UTC
README
ProxyManager 的 Laravel 实现。
为什么?
当你进行密集的构造函数注入时,需要许多对象来创建你的应用程序。由于 PHP 为每个请求创建所有环境,这对 PHP 来说是一项繁重的任务,而且可能你的对象图大部分都不会被使用。
此软件包通过提供代理而不是真实对象来帮助你。
关于此的更详细解释,请阅读 @Ocramius 对其的评论 或访问 ProxyManager 文档
用法
Laravel 的架构在 IoC 容器方面不够灵活:`Illuminate\Foundation\Application` 对象扩展了 `Illuminate\Container\Container`,这使得替换变得困难。
此软件包提供两个扩展,即 `Application` 和 `Container`。你可能不需要两者都使用。
此外,此软件包还提供了一种通过 `Specification` 模式来决定 IoC 容器将代理哪些对象的方法。
// Proxy all the things! $specification = new Proxyvel\Specifications\ProxyEverything; // Proxy by the given namespaces $specification = new Proxyvel\Specifications\ProxyNamespace([ 'App\Services', 'App\Repositories' ]); // Proxy only the given cases / class names $specification = new Proxyvel\Specifications\ProxyCases([ // You can always proxy Laravel's services by using the key Laravel sets 'db', // Proxy some concrete classes 'App\Services\FooService', // And some interfaces 'App\Contracts\FooRepositoryInterface' ]); // Proxy by regular expression (powerful, but usually complex) $specification = new Proxyvel\Specifications\ProxyByRegExp([ '/Interface$/', '/^Abstract/' ]); // Combine multiple specifications $specification = new Proxyvel\Specifications\ProxyCollection([ new Proxyvel\Specifications\ProxyCases(/* ... */), new Proxyvel\Specifications\ProxyNamespace(/* ... */), ]); // Define by negation (for those of you who see the glass half-empty) $specification = new Proxyvel\Specifications\ProxyNegator( new Proxyvel\Specifications\ProxyNamespace('App\Entities') );
Laravel 项目的用法
这里没有 `ServiceProvider`。你需要编辑你的 `bootstrap/start.php` 文件,并将 `$app` 变量替换为此软件包的 `Application`。
// in bootstrap/start.php $app = new Proxyvel\Application; // If you don't call this, the container will just defer to Laravel's default behavior $app->setProxyConfiguration( // Example Specification, build the one you need here new Proxyvel\Specifications\ProxyEverything, // Only instances of AbstractLazyFactory are accepted for now new ProxyManager\Factory\LazyLoadingValueHolderFactory );
在 Laravel 项目中,每个 `Container` 实例都是通过初始 `Application` 解析的,所以你只需使用这一点。
在 Laravel 项目之外的用法
如果你在 Laravel 项目之外使用 Laravel 的 `Container`,你需要实例化此软件包的 `Container` 扩展。
// Wherever you first instantiate it $container = new Proxyvel\Container( // Example Specification, build the one you need here new Proxyvel\Specifications\ProxyEverything, // Only instances of AbstractLazyFactory are accepted for now new ProxyManager\Factory\LazyLoadingValueHolderFactory );
由于 Liskov 替换原则,此软件包的扩展可以在任何期望 `Container` 的地方使用。