guiwoda/proxyvel

该包已被弃用,不再维护。作者建议使用 LaravelBA/proxyvel 包。

laravel的IoC容器服务代理

dev-master 2015-02-19 14:47 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:44:21 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》文件,并用这个包的《Application》替换《$app》变量。

// 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》的任何地方使用。