簡體   English   中英

Laravel 5.4常量值轉換

[英]Laravel 5.4 translations with constant values

我遇到翻譯問題。 我對他們很陌生,因為我從未嘗試將翻譯添加到項目中。 我在Laravel 5.4中使用此模型來進行通知:

// /App/Notification.php
class Notification extends Model
{
    const NO_STATUS = 0;
    const SENT      = 100;
    const ACCEPTED  = 200;
    const ERROR     = 300;

    public static $statuses = [
        self::NO_STATUS => 'No status',
        self::SENT      => 'Sent',
        self::ACCEPTED  => 'Accepted',
        self::ERROR     => 'Error',
    ];
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'from', 'to', 'status',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        //
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'from' => 'integer',
        'status' => 'integer',
    ];

    public function isSent()
    {
        return $this->status == self::SENT;
    }

    public function isAccepted()
    {
        return $this->status == self::ACCEPTED;
    }

    public function isError()
    {
        return $this->status == self::ERROR;
    }

    public static function statuses()
    {
        return self::statuses();
    }

    public function getStatusAttribute($value)
    {
       return self::$statuses[$value];
    }
}

我有這個轉換文件,我打算用它來將用戶狀態中存儲在數據庫中的數值轉換為可讀文本,以便用戶在視圖中看到通知列表時:

// /resources/lang/en/constants.php
return [

    /*
     * Notifications constants
     */
    'notification' => [
        'no_status' => 'No status',
        'sent'      => 'Sent',
        'accepted'  => 'Accepted',
        'error'     => 'Error',
    ],
];

我在模型中具有getStatusAttribute訪問器函數,以文本形式檢索其狀態代碼,但是我不能(顯然)將值設置為靜態屬性,如下所示:

public static $statuses = [
    self::NO_STATUS => trans('constants.notification.no_status'),
    self::SENT      => trans('constants.notification.sent'),
    self::ACCEPTED  => trans('constants.notification.accepted'),
    self::ERROR     => trans('constants.notification.error'),
];

關於如何實現此目標的任何建議?

我希望對象中返回的屬性已經成為翻譯后的文本,如果可能的話,請在視圖中進行翻譯。

謝謝你的時間。

您應該返回一個函數,而不是一個常量。

Class Status
{
    public static function getStatusArray = [
        self::NO_STATUS => __('constants.notification.no_status'),
        self::SENT      => __('constants.notification.sent'),
        self::ACCEPTED  => __('constants.notification.accepted'),
        self::ERROR     => __('constants.notification.error'),
    ];
} 

之后,您可以像這樣調用一個函數:

array_get(App\Class::getStatusArray(), 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM