如何在 Laravel 5.4.18 中使用特征?

How to use traits in Laravel 5.4.18?

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

-我没有更改框架中的任何文件夹,一切都在它对应的地方-

从已经非常感谢你。

我在 Http 目录中创建了一个名为 BrandsTrait.php

的 Traits 目录

并像这样使用它:

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

特质描述:

Traits 是一种在单继承语言(例如 PHP 中进行代码重用的机制。 Trait 旨在通过使开发人员能够在生活在不同 class 层次结构中的多个独立 classes 中自由重用方法集来减少单一继承的一些限制。 Traits 和 classes 组合的语义以一种降低复杂性并避免与多重继承和 Mixins 相关的典型问题的方式定义。

解决方法

在你的应用中创建一个目录,命名为Traits

Traits 目录(文件:Sample.php)中创建您自己的特征:

<?php

namespace App\Traits;

trait Sample
{
    function testMethod()
    {
        echo 'test method';
    }
}

然后在自己的控制器中使用:

<?php
namespace App\Http\Controllers;

use App\Traits\Sample;

class MyController {
    use Sample;
}

现在 MyController class 里面有 testMethod 方法。

您可以通过在 MyController class:

中覆盖它们来更改特征方法的行为
<?php
namespace App\Http\Controllers;

use App\Traits\Sample;

class MyController {
    use Sample;

    function testMethod()
    {
        echo 'new test method';
    }
}

让我们看一个特征示例:

namespace App\Traits;

trait SampleTrait
{
    public function addTwoNumbers($a,$b)
    {
        $c=$a+$b;
        echo $c;
        dd($this)
    }
}

然后在另一个 class 中,只需导入特征并将函数与 this 一起使用,就好像该函数在 class:

的本地范围内一样
<?php

namespace App\ExampleCode;

use App\Traits\SampleTrait;

class JustAClass
{
    use SampleTrait;
    public function __construct()
    {
        $this->addTwoNumbers(5,10);
    }
}