2016-04-15 13 views
24

私はTraitsを使い慣れていませんが、私の機能では繰り返しているコードがたくさんありますし、Traitを使ってコードを乱雑にしたいのです。私はと呼ばれる特性で私のHttpディレクトリにTraitsディレクトリを作った。それはすべてのブランドを呼び出すことだけです。しかし、私はこのように、私の製品コントローラーにBrandsTraitを呼び出すしようとすると:Traits - Laravelの使い方5.2

use App\Http\Traits\BrandsTrait; 

class ProductsController extends Controller { 

    use BrandsTrait; 

    public function addProduct() { 

     //$brands = Brand::all(); 

     $brands = $this->BrandsTrait(); 

     return view('admin.product.add', compact('brands')); 
    } 
} 

それは私の方法は、[BrandsTrait]は存在しませんというエラーを与えます。何かを初期化するか、別の方法で呼び出すと思いますか?

はここで多くのクラスで共有することができます別の場所にあなたのクラスのセクションを定義するような形質の私のBrandsTrait.php

<?php 
namespace App\Http\Traits; 

use App\Brand; 

trait BrandsTrait { 
    public function brandsAll() { 
     // Get all the brands from the Brands Table. 
     Brand::all(); 
    } 
} 

答えて

30

だと思います。あなたのクラスにuse BrandsTraitを置くことによって、そのセクションがあります。あなたが書きたい何

はあなたの特性のメソッドの名前である

$brands = $this->brandsAll(); 

です。

また、brandsAllメソッドに戻り値を追加することを忘れないでください。

+0

ああ、わからなかった、私の間違い。ありがとうございました。 – David

+1

私はこれを継承で達成することができますが、それにはどのような特徴がありますか? –

+6

PHPは複数の継承をサポートしていないため、単一のクラスのみを継承することができます。しかし、特質によって、あなたは好きなだけ多くを使うことができます。 – maddockst

2
use App\Http\Traits\BrandsTrait; 

class ProductsController extends Controller { 

    use BrandsTrait; 

    public function addProduct() { 

     //$brands = Brand::all(); 

     $brands = $this->brandsAll(); 

     return view('admin.product.add', compact('brands')); 
    } 
}