How to use traits in Laravel 5.4.18?

最后都变了- 提交于 2019-12-01 06:07:17

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

Trait description:

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.

The solution

Make a directory in your App, named Traits

Create your own trait in Traits directory ( file: Sample.php ):

<?php

namespace App\Traits;

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

Then use it in your own controller:

<?php
namespace App\Http\Controllers;

use App\Traits\Sample;

class MyController {
    use Sample;
}

Now the MyController class has the testMethod method inside.

You can change the behavior of trait methods by overriding them it in MyController class:

<?php
namespace App\Http\Controllers;

use App\Traits\Sample;

class MyController {
    use Sample;

    function testMethod()
    {
        echo 'new test method';
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!