Laravel 5.4具有常数值的翻译

时间:2017-07-26 11:26:55

标签: php laravel-5

我遇到翻译问题。我对它们很新,因为我从未尝试过将翻译添加到项目中。我在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访问器函数来检索其状态代码作为文本,但我无法将值设置为静态属性(obviusly),如下所示:

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'),
];

关于如何实现这一目标的任何建议?

我希望对象中返回的属性已成为翻译文本,而不是在视图中翻译它,如果可能的话。

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

您应该返回一个函数,而不是一个常量。

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)
相关问题