2016-10-24 8 views
0

私はTFAというインターフェースとGoogleTFAというインプリメンテーションを持っています。これは私の方法であるユーザーモデルでバインドが機能しない

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

:しかし、私は私のユーザモデルにTFAを使用しようとするたびに私はこのエラーを取得

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); 

あなたは、いくつかの異なる方法でこれを使用している場合、私はそれ自身のメソッドに上記を移動します。

また、あなたは(下の例では、あなたは自分のApp名前空間であなたのファサードを配置することがありますと仮定している)あなたのTFA実装のために特別にFacadeを作成することができます。

は、ファイルapp/Facades/Tfa.phpを作成し、そこに以下を追加:

012:

<?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配列に以下を追加

あなただけのファサードから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よく定義する –

+0

クリーン、私は最もクリーンなコードを取得しようとしています。他の解決策はありますか?モデルでDIを有効にすることはできますか? – Martin

関連する問題