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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:08:38  来源:igfitidea点击:

Laravel 5.5 Override vendor class

phplaravel

提问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\Classwith App\Vendor\MyCustomClass

但这会失败,因为构造函数依赖于当时不可用的其他变量。我真的只需要该应用程序来覆盖对Vendor\VendorName\Classwith 的任何调用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 Registermethod

它扩展了供应商服务提供者(在 config/app.php 中找到)。在该 ServiceProvider 中,在重写的Register方法中添加我的别名

 $loader->alias('Vendor\VendorName\Class', 'App\Vendor\MyCustomClass');