我是 Traits 的新手,但我的函数中有很多重复的代码,我想使用 Traits 使代码不那么困惑。我在我的 Http
目录中创建了一个 Traits
目录,其中包含一个名为 BrandsTrait.php
的 Trait。它所做的只是呼吁所有品牌。但是当我尝试在我的产品 Controller 中调用 BrandsTrait 时,如下所示:
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'));
}
}
它给我一个错误,提示 Method [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();
}
}
最佳答案
考虑一下特性,例如在不同的地方定义你的类的一部分,它可以被许多类共享。通过在你的类中放置 use BrandsTrait
它有那个部分。
你要写的是
$brands = $this->brandsAll();
这是你的 trait 中方法的名称。
另外 - 不要忘记在您的 brandsAll
方法中添加一个返回值!
关于php - 如何使用特征 - Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36657629/