php 如何使用 Traits - Laravel 5.2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36657629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:52:20  来源:igfitidea点击:

How to use Traits - Laravel 5.2

phplaravellaravel-5.2traits

提问by David

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. I have made a Traitsdirectory in my Httpdirectory with a Trait called BrandsTrait.php. And all it does is call on all Brands. But when I try to call BrandsTrait in my Products Controller, like this:

我是 Traits 的新手,但我的函数中有很多重复的代码,我想使用 Traits 使代码不那么混乱。我Traits在我的Http目录中创建了一个名为BrandsTrait.php. 它所做的就是调用所有品牌。但是当我尝试在我的产品控制器中调用 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.Am I suppose to initialize something, or call it differently?

它给了我一个错误,说Method [BrandsTrait] 不存在。我是想初始化一些东西,还是用不同的方式称呼它?

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

回答by Scopey

Think of traits like defining a section of your class in a different place which can be shared by many classes. By placing use BrandsTraitin your class it has that section.

想想traits,比如在不同的地方定义你的类的一个部分,可以被许多类共享。通过放置use BrandsTrait在您的班级中,它具有该部分。

What you want to write is

你想写的是

$brands = $this->brandsAll();

That is the name of the method in your trait.

那就是你的 trait 中方法的名称。

Also - don't forget to add a return to your brandsAllmethod!

另外 - 不要忘记在你的brandsAll方法中添加一个 return !

回答by Sonford Son Onyango

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