fer-projekt / laravel-proxy
Laravel代理特性,用于解析给定契约的当前绑定值。
dev-main
2023-10-25 22:17 UTC
Requires
- php: ^8.0
Requires (Dev)
- illuminate/container: ^9.0|^10.0
- illuminate/support: ^9.0|^10.0
- orchestra/testbench: ^7.0|^8.0
This package is auto-updated.
Last update: 2024-09-26 00:29:52 UTC
README
Laravel代理特性,用于解析给定契约的当前绑定值。
安装
您可以通过composer安装此包
composer require fer-projekt/laravel-proxy
用法
轻松交换容器绑定,而无需修改代码库中的任何其他内容。
namespace App\Models; use Ecommerce\Models\Product as BaseProduct; class Product extends BaseProduct { // }
在您创建自定义模型后,您可以将产品契约的容器绑定进行交换。您可以在服务提供者的register
方法中这样做
use App\Models\Product; use Ecommerce\Contracts\Product as Contract; public function register() { $this->app->bind(Contract::class, Product::class); }
注意,您应该扩展基础模型然后将其绑定到接口。
代理
代理代表当前绑定到容器中的类。您通常不会使用这些很多,但在某些情况下——例如,当您开发包或扩展时——代理可能会很方便。
use Ecommerce\Models\Product; // Available proxy methods Product::proxy(); Product::getProxiedClass(); Product::getProxiedContract(); // Proxied calls to the bound instance Product::proxy()->newQuery()->where(...); Product::proxy()->variation(...); // Dynamic usage of bound classes public function product() { $this->belongsTo(Product::getProxiedClass()); }
Laravel Proxy提供了InteractsWithProxy
特性,使得所需的类可代理。该特性包含抽象方法,可以从容器中自动解析代理类
namespace App\Models; use App\Contracts\Models\Addon as Contract; use FerProjekt\LaravelProxy\InteractsWithProxy; use Illuminate\Databse\Eloquent\Model; class Addon extends Model implements Contract { use InteractsWithProxy; /** * Get the proxied interface. * * @return string */ public static function getProxiedInterface(): string { return Contract::class; } }
此外,我们还需要在服务提供者中将契约绑定到容器
public function register(): void { $this->app->bind(\App\Contracts\Models\Addon::class, \App\Models\Addon::class); }
从这一点开始,我们的Addon
模型是可代理的,这意味着如果我们在容器中交换绑定,代理类将是当前绑定值而不是原始值。这为我们扩展应用程序或使用包提供了更多灵活性。
// Use the Addon proxy Addon::proxy()->newQuery();
开发
从github克隆此包
git clone https://github.com/fer-projekt/laravel-proxy.git
cd laravel-proxy
启动和停止docker
docker-compose up -d
docker-compose down
通过composer安装依赖项并进行测试
docker-compose exec app bash
composer update
phpunit
致谢
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。