2016-02-12 90 views

回答

1

沒有最好的辦法,但option - 1不是一個選擇,根本不是,至少對於擴展組件/類。

無論如何,Laravel框架提供了擴展自己的包的不同方法。例如,框架有幾個Manager classes管理基於驅動程序的組件的創建。這些包括the cache,session,authenticationqueue組件。管理員類負責根據應用程序的配置創建特定的驅動程序實現。

每個管理者都包括延伸方法,該方法可以用於容易地注入新的驅動程序解析功能到manager.In這種情況下,可以延長cache,例如,使用這樣的事情:

Cache::extend('mongo', function($app) 
{ 
    return Cache::repository(new MongoStore); 
}); 

但這並非全部,只是使用管理器擴展組件的一種方式。像你提到的Service Provider一樣,是的,這是擴展組件的另一種選擇。在這種情況下,您可以擴展組件的服務提供者類並交換提供者數組。 Laravel網站有專門的章節,請查詢the documentation

0

供應商文件通常是命名空間。你自己的軟件包/代碼將會/應該被命名空間。使用這個,我會創建自己的包,並依賴於其他Vendor包,然後創建自己的類來擴展他們的包。

<?php namespace My\Namespace\Models 
class MyClass extends \Vendor3\Package\VendorClass { 
    // my custom code that enhances the vendor class 
} 

您絕不應該考慮更改供應商的軟件包。雖然可以這樣做,但防止這些變化消失的維護要求變得繁重。 (即供應商更新是他們的軟件包,您的更改風險將消失)。將供應商數據作爲基礎進行處理,然後構建基礎,而不是修改基礎,實際上使代碼更易於維護和使用。 IMO。

0

如果需要,您可以擴展或定製服務提供商,然後在您的應用配置中註冊它們。例如,我最近需要創建自己的密碼重置服務提供程序。

首先我創建了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 
], 

有可能是另一種方式來達到同樣的效果,但是這是很好的和容易。

相關問題