如何在Laravel中进行特质 [英] How to make a Trait in Laravel

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

问题描述

如果我想在我的模型上使用此特征,在哪里制作文件

Where to make the file if i want to use this trait on my Models

如果我想在内部具有此特征,该文件应如何显示:

How should this file look like if i want to have this trait inside:

trait FormatDates
{
    protected $newDateFormat = 'd.m.Y H:i';


    // save the date in UTC format in DB table
    public function setCreatedAtAttribute($date){

        $this->attributes['created_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getCreatedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }

    // save the date in UTC format in DB table
    public function setUpdatedAtAttribute($date){

        $this->attributes['updated_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getUpdatedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }

    // save the date in UTC format in DB table
    public function setDeletedAtAttribute($date){

        $this->attributes['deleted_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getDeletedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }
}

以及如何将其应用于例如用户模型类...

And how to apply it for example on a User Model class...

推荐答案

好吧,laravel跟随PSR-4,所以您应该将特征放置在

Well, laravel follows PSR-4 so you should place your traits in:

app/Traits

然后,您需要确保使用该路径对特征进行命名空间,所以放置:

You then need to make sure you namespace your trait with that path, so place:

namespace App\Traits;

trait

然后确保在保存文件时,文件名与特征名称匹配.因此,如果您的特征称为FormatDates,则需要将文件另存为FormatDates.php

Then make sure when you save the file, the file name matches the trait name. So, if your trait is called FormatDates you need to save the file as FormatDates.php

然后通过添加以下内容在用户模型中使用"它:

Then 'use' it in your User model by adding:

use App\Traits\FormatDates;

在模型的顶部,但在namespace

然后添加:

use FormatDates;

就在类内部,因此对于您的User模型,假设您使用的是laravel默认值,则会得到:

just inside the class, so for your User model, assuming you are using the laravel default, you would get:

use App\Traits\FormatDates;

class User extends Authenticatable
{
    use Notifiable, FormatDates;

...
}

并记得转储自动加载器:

And remember to dump the autoloader:

composer dump-autoload

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

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