Laravel 5.5 覆盖供应商类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47925618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.5 Override vendor class
提问by Kiksy
I'm trying to override (not extend) a vendor class. So whenever the vendor class gets called (within the vendor code), I want it to call my custom class.
我正在尝试覆盖(而不是扩展)供应商类。因此,无论何时调用供应商类(在供应商代码中),我都希望它调用我的自定义类。
It looks like I need to alias the class in my App/Providers/AppServiceProvider
看起来我需要在我的类中别名 App/Providers/AppServiceProvider
I've tried this:
我试过这个:
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Vendor\VendorName\Class', 'App\Vendor\MyCustomClass');
But this doesn't do anything.
但这没有任何作用。
I can get my class registered fine:
我可以很好地注册我的课程:
$this->app->register(
'App\Vendor\MyCustomClass'
);
But this then fails as the constructor relys on other variables not available at that point. I literally just need the app to override any call to Vendor\VendorName\Class
with App\Vendor\MyCustomClass
但这会失败,因为构造函数依赖于当时不可用的其他变量。我真的只需要该应用程序来覆盖对Vendor\VendorName\Class
with 的任何调用App\Vendor\MyCustomClass
回答by Kiksy
So the solution was create a new ServiceProvider
所以解决方案是创建一个新的 ServiceProvider
php artisan make:provider MyServiceProvider
Which extended the Vendor service provider (found within config/app.php). Within that ServiceProvider, add my alias within the overridden Register
method
它扩展了供应商服务提供者(在 config/app.php 中找到)。在该 ServiceProvider 中,在重写的Register
方法中添加我的别名
$loader->alias('Vendor\VendorName\Class', 'App\Vendor\MyCustomClass');