2016-10-24 33 views
0

我有一個名爲TFA的接口和一個名爲GoogleTFA的實現。但每次我嘗試使用TFA在我的用戶模型,我得到這個錯誤:綁定在用戶模型上不起作用

Type error: Argument 1 passed to App\Models\User::toggleTFA() must implement interface App\Contracts\TFA, none given

這是我的方法:

public function toggleTFA(TFA $tfa) 
    { 
     /** 
     * If we're disabling TFA then we reset his secret key. 
     */ 
     if ($this->tfa === true) 
      $this->tfa_secret_key = $tfa->getSecretKey(); 

     $this->tfa = !$this->tfa; 
     $this->save(); 
    } 

,這是我對AppServiceProvider.php綁定:

public function register() 
    { 
     /** 
     * GoogleTFA as default TFA adapter. 
     */ 
     $this->app->bind('App\Contracts\TFA', 'App\Models\GoogleTFA'); 
    } 

任何想法,爲什麼我有這種行爲?如果我在我的控制器的任何方法上鍵入提示TFA $ tfa,它的工作原理,但我試圖保持我的邏輯模型。提前致謝。

+0

你能否提供一些更多的信息,如你打電話給** toggleTFA ** – Haridarshan

回答

1

DI不適用於每種方法。控制器方法將使用此爲Laravel爲您解決它們。

一種方式來得到這個模型中的工作是手動解決它:

$tfa = app(TFA::class); 

如果你在幾個不同的方法使用此我將上述移動到它自己的方法。

或者,你可以創建一個Facade專門爲您TFA實現(下面的例子是假設你只是把你的門面在App命名空間):

創建文件app/Facades/Tfa.php並添加以下到它:

<?php 

namespace App\Facades; 

use Illuminate\Support\Facades\Facade; 

class Tfa extends Facade 
{ 
    /** 
    * Get the registered name of the component. 
    * 
    * @return string 
    */ 
    protected static function getFacadeAccessor() 
    { 
     return 'App\Contracts\TFA'; 
    } 

} 

然後你config/app.php添加以下到aliases陣列底部:

'Tfs' => App\Facades\Tfs::class, 

這樣你就可以只調用從門面getSecretKey

public function toggleTFA() 
{ 
    /** 
    * If we're disabling TFA then we reset his secret key. 
    */ 
    if ($this->tfa === true) 
     $this->tfa_secret_key = Tfa::getSecretKey(); 

    $this->tfa = !$this->tfa; 
    $this->save(); 
} 

希望這有助於!

+0

沒有更好的解決方案嗎? – Martin

+0

@Martin Define better –

+0

Cleanest,我試圖得到最乾淨的代碼。還有其他解決方案嗎?我可以在模型上啓用DI嗎? – Martin

相關問題