如何使用特质-Laravel 5.2 [英] How to use Traits - Laravel 5.2

查看:68
本文介绍了如何使用特质-Laravel 5.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Traits的新手,但是我的函数中有很多重复的代码,并且我想使用Traits来减少代码的混乱度.我已经在我的Http目录中创建了一个Traits目录,并具有一个名为BrandsTrait.php的特征.它所做的就是呼吁所有品牌.但是,当我尝试在我的产品控制器中调用BrandsTrait时,就像这样:

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 Traits directory in my Http directory 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:

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]不存在.我是否应该初始化某些内容,或者以不同的方式调用它?

it gives me an error saying Method [BrandsTrait] does not exist. Am I suppose to initialize something, or call it differently?

这是我的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放在您的班级中,它具有该部分.

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.

你想写的是

$brands = $this->brandsAll();

这是特征中方法的名称.

That is the name of the method in your trait.

此外-不要忘记在您的brandsAll方法中添加返回值!

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

这篇关于如何使用特质-Laravel 5.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆