扩展laravel供应商包的最佳方式是什么?
1-将软件包复制到我自己的应用程序/软件包并更改它?
2-使用服务提供者扩展类?
3-或者其他的东西?
发布于 2016-02-13 01:29:13
没有最好的方法,但option - 1不是一个选择,至少对于扩展组件/类来说不是。
无论如何,Laravel框架提供了不同的方式来扩展它自己的包。例如,框架有几个Manager classes来管理基于驱动程序的组件的创建。这些组件包括the cache、session、authentication和queue组件。manager类负责基于应用程序的配置创建特定的驱动程序实现。
这些管理器中的每一个都包含一个extend方法,该方法可用于轻松地将新的驱动程序解析功能注入manager.In。在这种情况下,您可以扩展cache,例如,使用如下代码:
Cache::extend('mongo', function($app)
{
return Cache::repository(new MongoStore);
});但这并不是全部,而是使用管理器扩展组件的一种方式。就像你提到的Service Provider,是的,这是扩展组件的另一种选择。在这种情况下,您可以扩展组件的服务提供程序类并交换提供程序数组。在Laravel网站上有一个专门的章节,请查看the documentation。
发布于 2016-02-13 01:35:20
供应商文件通常采用命名空间。您自己的包/代码也将/应该命名为空间。使用这个,我将创建自己的包,依赖于其他供应商的包,然后创建我自己的类来扩展他们的类。
<?php namespace My\Namespace\Models
class MyClass extends \Vendor3\Package\VendorClass {
// my custom code that enhances the vendor class
}您永远不应该考虑更改供应商的软件包。虽然这是可以做到的,但防止这些更改消失的维护要求变得非常繁重。(例如,供应商更新是他们的包,您的更改可能会消失)。将供应商数据视为基础,然后在其上构建,而不是修改基础,实际上会使您的代码更易于维护和使用。国际海事组织。
发布于 2016-02-13 02:07:25
如果需要,您可以扩展或自定义服务提供商,然后在应用程序配置中注册它们。例如,我最近需要创建自己的密码重置服务提供商。
首先,我在/app/Auth/Passwords/中创建了2个自定义文件
PasswordResetServiceProvider.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);
}
}PasswordBroker.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
],可能还有另一种方法可以实现相同的结果,但这很容易实现。
https://stackoverflow.com/questions/35368265
复制相似问题