簡體   English   中英

在Laravel中,我如何非靜態啟動特征

[英]In Laravel, how can I boot trait non-statically

是否有任何理由為什么我們只有這種靜態方式來啟動Laravel中的特征:

static function bootMyTrait ()
{...}

有沒有辦法啟動trait並在啟動函數中有模型實例? 像這樣:

function bootMyTrait ()
{
    if ($this instanceOf awesomeInterface)
    {
        $this->append('nice_attribute');
    }
}

我需要這個AF,並且很長一段時間沒有找到任何解決方案。

Laravel 5.7開始,您可以使用特征初始化器 ,而不是特征引導器 我有同樣的任務,能夠像這樣解決它:

public function initializeMyTrait()
{
    if ($this instanceOf awesomeInterface)
    {
        $this->append('nice_attribute');
    }
}

好吧,似乎沒有人關心:D

好消息是,在15分鍾內,我已經用基本模型解決了我的問題:

public function __construct(array $attributes = [])
{

    foreach (class_uses_recursive($this) as $trait)
    {
        if (method_exists($this, $method = 'init'.class_basename($trait))) {
            $this->{$method}();
        }
    }

    parent::__construct($attributes);
}

編輯

不要依賴於特征,而是使用Eloquent的訪問器和變異器。 例如,在User模型上定義以下方法:

// Any time `$user->first_name` is accessed, it will automatically Uppercase the first letter of $value
public function getFirstNameAttribute($value)
{
    return ucfirst($value);
}

這會將$user->first_name屬性附加到模型。 通過在方法名稱前加上get ,並使用Attribute后綴,你告訴Eloquent,嘿,這是我模型的實際屬性。 它不需要存在於表中。

另一方面,您可以定義一個mutator:

// Any string set as first_name will automatically Uppercase words.
public function setFirstNameAttribute($value)
{
    $this->attributes['first_name'] = ucwords($value);
}

這將在$attributes數組中設置之前將您執行的任何操作應用於$value

當然,您可以將這些應用於數據庫表中存在的屬性。 如果您有原始的,未格式化的數據,例如電話號碼1234567890,並且您想要應用國家/地區代碼,則可以使用訪問器方法來屏蔽該數字,而無需修改數據庫中的原始值。 另一方面,如果您想將標准格式應用於值,則可以使用mutator方法,以使所有數據庫值符合通用標准。

Laravel Accessor和Mutators

暫無
暫無

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

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