简体   繁体   English

如何使用Traits - Laravel 5.2

[英]How to use Traits - Laravel 5.2

I'm new to Traits, but I have a lot of code that is repeating in my functions, and I want to use Traits to make the code less messy. 我是Traits的新手,但是我的函数中有很多重复的代码,我想使用Traits来减少代码的混乱。 I have made a Traits directory in my Http directory with a Trait called BrandsTrait.php . 我已经做了Traits目录在我Http目录下有一个名为特质BrandsTrait.php And all it does is call on all Brands. 它所做的只是呼吁所有品牌。 But when I try to call BrandsTrait in my Products Controller, like this: 但是当我尝试在我的产品控制器中调用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'));
    }
}

it gives me an error saying Method [BrandsTrait] does not exist. 它给我一个错误,说方法[BrandsTrait]不存在。 Am I suppose to initialize something, or call it differently? 我想初始化一些东西,或者用不同的方式称呼它?

Here is my BrandsTrait.php 这是我的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();
    }
}

Think of traits like defining a section of your class in a different place which can be shared by many classes. 考虑一下这样的特征,比如在不同的地方定义一个类的一部分,可以由许多类共享。 By placing use BrandsTrait in your class it has that section. 通过在您的班级中use BrandsTrait ,它具有该部分。

What you want to write is 你想写的是

$brands = $this->brandsAll();

That is the name of the method in your trait. 这是特征中方法的名称。

Also - don't forget to add a return to your brandsAll method! 此外 - 不要忘记为您的brandsAll添加返回brandsAll方法!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM