简体   繁体   English

Laravel 5.5覆盖供应商类

[英]Laravel 5.5 Override vendor class

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 我真的只需要应用程序覆盖对App\\Vendor\\MyCustomClass Vendor\\VendorName\\Class任何调用

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). 这扩展了供应商服务提供商(在config / app.php中找到)。 Within that ServiceProvider, add my alias within the overridden Register method 在该ServiceProvider中,在重写的Register方法中添加我的别名

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM