2017-11-01 5 views
1

私Laravelアプリケーションを維持し、私は以下のソリューション行った重複コードの多くから自分自身を保存するには:Laravel:拡張コントローラーやTraitなどを使用しますか?

をBaseController

class BaseController extends Controller 
{ 
    public function get($id){ 
     return $this->baseService->get($id); 
    } 

    public function getAll(){ 
     return $this->baseService->getAll(); 
    } 
} 

BaseService

class BaseService 
{ 
    protected $model; 

    public function __construct($model){ 
     $this->model = $model; 
    } 

    public function get($id){ 
     return response()->json($this->model->where('id', $id)->first()); 
    } 

    public function getAll() 
    { 
     return $this->model->get(); 
    } 
} 

MyController

class MyController extends BaseController 
{ 
    protected $model; 
    protected $baseService; 

    public function __construct(){ 
     $this->model= new Model(); 
     $this->baseService = new BaseService($this->model); 
    } 

    /** 
    * This controller has all the functionality from BaseController now 
    */ 
} 

これは良い方法であると私は思っています。私はこれに固執すべきか、あるいは私は別のアプローチをとるべきですか?私はTraitsについて聞いたことがあるが、同じことをしているかどうかは分からない。それは私が使っているLaravel 5.5です。

答えて

1

はい、特性が定期的にコントローラの外にメソッドを移動するために使用されています。 Laravelフレームワークが使用する良い例はThrottlesLogin特性です。 https://github.com/laravel/framework/blob/5.5/src/Illuminate/Foundation/Auth/ThrottlesLogins.php#L20 を見て、メソッドがコントローラの外でどのように移動されたかを確認しますが、useキーワードを使用してその特性をインポートすることによって引き続きアクセスできます。

あなたのユースケースに適した特性はありますが、探している機能には使用しません。私はレポジトリパターンを使用します。コードを分離して再利用しやすくする方がよいでしょう。

リポジトリパターンの詳細については、https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/を参照してください。基本的には、コードを別のリポジトリに分割し、IoCに組み込まれたLaravelを使用してリポジトリをコントローラに注入します。提案や情報のため

MyController

class MyController extends Controller 
{ 
    protected $repo; 

    public function __construct(MyRepository $myRepository) 
    { 
    $this->repo = $myRepository; 
    } 

    public function index() 
    { 
     $myStuff = $this->repo->all(); 
    } 

    // you can also inject the repository directly in the controller 
    // actions. 
    // look at https://laravel.com/docs/5.5/controllers#dependency-injection-and-controllers 
    public function other(MyRepository $repo) 
    { 
     $myStuff = $repo->all(); 
    } 
} 
+0

ありがとう、これは本当に有用な素材です。私は見てみましょう。 –

1

これは、特性の完全な使用例です。形質は再利用可能な機能を意図しています。彼らは非常に簡単に実装することができますし、あなたが持っているものを変更するために数分以上かかることはありません。ここで

はそれらの素晴らしい記事です:https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5

+0

感謝。 @WarrenRが提案したように、このユースケースでは、特性よりもリポジトリパターンを選択しましたか? –

+0

この特性を使用する唯一のものがデータベースのやりとりであれば、リポジトリパターンを使用できます。私が示唆する唯一のことは、それが価値があるかどうかを自分自身に尋ねることです。私の考えでは、私の見解では、実装するのがはるかに簡単で、3か月後にすべてが何を意味しているのかを忘れてしまうのは簡単です。 –

関連する問題