如何在Laravel 5.4.18中使用特征? [英] How to use traits in Laravel 5.4.18?

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

问题描述

我需要一个示例,该示例确切说明在何处创建文件,如何写入文件以及如何使用特征中声明的函数. 我使用Laravel Framework 5.4.18

-我尚未更改框架中的任何文件夹,所有内容均与之相对应-

非常感谢您.

解决方案

我已经在我的Http目录中创建了一个Traits目录,并具有一个名为BrandsTrait.php

的Trait.

并像这样使用它:

use App\Http\Traits\BrandsTrait;

class YourController extends Controller {

    use BrandsTrait;

    public function addProduct() {

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

        // $brands = $this->BrandsTrait();  // this is wrong
        $brands = $this->brandsAll();
    }
}

这是我的BrandsTrait.php

<?php
namespace App\Http\Traits;

use App\Brand;

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

        return $brands;
    }
}

注意:就像在某些namespace中编写的普通函数一样,您也可以使用traits

I need an example of where to exactly create the file, to write to it, and how to use the functions declared in the trait. I use Laravel Framework 5.4.18

-I have not altered any folder in the framework, everything is where it corresponds-

From already thank you very much.

解决方案

I have Create a Traits directory in my Http directory with a Trait called BrandsTrait.php

and use it like:

use App\Http\Traits\BrandsTrait;

class YourController extends Controller {

    use BrandsTrait;

    public function addProduct() {

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

        // $brands = $this->BrandsTrait();  // this is wrong
        $brands = $this->brandsAll();
    }
}

Here is my BrandsTrait.php

<?php
namespace App\Http\Traits;

use App\Brand;

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

        return $brands;
    }
}

Note: Just like a normal function written in a certain namespace, you can use traits as well

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

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