扩展Laravel供应商软件包的最佳方法是什么?
1 - 将包复制到我自己的应用程序/包并更改它?
2 - 使用服务提供商扩展类?
3 - 还是别的什么?
没有最好的方法,但option - 1
不是一种选择,根本不是一种选择,至少对于扩展组件/类而言。
无论如何,Laravel框架提供了不同的方法来扩展它自己的软件包。例如,框架有几个Manager classes
来管理基于驱动程序的组件的创建。这些组件包括the cache
、session
、authentication
和queue
组件。管理器类负责根据应用程序的配置创建特定的驱动程序实现。
这些管理器中的每一个都包含一个扩展方法,可用于轻松地将新的驱动程序解析功能注入管理器。在这种情况下,您可以 扩展cache
,例如,使用如下内容:
Cache::extend('mongo', function($app)
{
return Cache::repository(new MongoStore);
});
但这还不是全部,而是使用管理器扩展组件的一种方式。就像你提到的Service Provider
,是的,这是扩展组件的另一种选择。在这种情况下,您可以扩展组件的服务提供商类并交换提供程序数组。Laravel网站上有一个专门的章节,请查看文档。
供应商文件通常具有命名空间。 你自己的包/代码也将/应该被命名。 使用它,我将创建自己的包,并依赖于其他供应商的包,然后创建自己的类来扩展他们的类。
<?php namespace My'Namespace'Models
class MyClass extends 'Vendor3'Package'VendorClass {
// my custom code that enhances the vendor class
}
您永远不应该考虑更改供应商的软件包。 虽然可以做到这一点,但防止这些更改消失的维护要求变得繁重。 (即供应商更新是他们的软件包,您的更改有消失的风险(。 将供应商数据视为基础,然后在其上构建,而不是修改基础,实际上使您的代码更易于维护和使用。 国际 海事 组织。
如果需要,可以扩展或自定义服务提供商,然后在应用配置中注册它们。例如,我最近需要创建自己的密码重置服务提供商。
首先,我在/app/Auth/Passwords/ 中创建了 2 个自定义文件
密码重置服务提供商.php
namespace App'Auth'Passwords;
use App'Auth'Passwords'PasswordBroker;
use Illuminate'Auth'Passwords'PasswordResetServiceProvider as BasePasswordResetServiceProvider;
class PasswordResetServiceProvider extends BasePasswordResetServiceProvider
{
protected function registerPasswordBroker()
{
// my custom code here
return new PasswordBroker($custom_things);
}
}
密码经纪人.php
namespace App'Auth'Passwords;
use Closure;
use Illuminate'Auth'Passwords'PasswordBroker as BasePasswordBroker;
class PasswordBroker extends BasePasswordBroker
{
public function sendResetLink(array $credentials, Closure $callback = null) {
// my custom code here
return 'Illuminate'Contracts'Auth'PasswordBroker::RESET_LINK_SENT;
}
public function emailResetLink('Illuminate'Contracts'Auth'CanResetPassword $user, $token, Closure $callback = null) {
// my custom code here
return $this->mailer->queue($custom_things);
}
}
现在我有了自定义类,我替换了/config/app 中的默认服务提供程序.php
'providers' => [
// a bunch of service providers
// Illuminate'Auth'Passwords'PasswordResetServiceProvider::class,
App'Auth'Passwords'PasswordResetServiceProvider::class, //custom
// the remaining service providers
],
可能还有另一种方法可以达到相同的结果,但这很好而且很容易。