如何在Laravel 5.4.18中使用特征?

emi*_*emi 6 php traits laravel

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

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

从非常感谢你.

May*_*eyz 11

我在我的Http目录中创建了一个Trait目录,其中有一个名为的TraitBrandsTrait.php

并使用它像:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:就像某个特定的普通函数一样namespace,你也可以使用traits

  • 请注意,这不是特征的预期用途.在这里使用它的方式,这将最好用作`存储库接口`.特征应该是旨在跨多个不同控制器/模型重用的特征. (4认同)

Roh*_*fii 9

特性说明:

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

解决方案

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

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

<?php

namespace App\Traits;

trait Sample
{
    function testMethod()
    {
        echo 'test method';
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<?php
namespace App\Http\Controllers;

use App\Traits\Sample;

class MyController {
    use Sample;
}
Run Code Online (Sandbox Code Playgroud)

现在这个MyControllertestMethod里面有这个方法。

您可以通过在MyController类中覆盖它们来更改 trait 方法的行为:

<?php
namespace App\Http\Controllers;

use App\Traits\Sample;

class MyController {
    use Sample;

    function testMethod()
    {
        echo 'new test method';
    }
}
Run Code Online (Sandbox Code Playgroud)


Pla*_*tta 6

让我们看一个示例特征:

namespace App\Traits;

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

然后在另一个类中,只需导入特征并使用该函数,this就好像该函数位于该类的本地范围内一样:

<?php

namespace App\ExampleCode;

use App\Traits\SampleTrait;

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