2016-11-23 79 views
0

在Laravel中,所有模型都扩展了基础模型。扩展Laravel的基础模型

laravel雄辩的模型有一个名为$日期的受保护的数组属性。每个添加到此数组的日期都会自动转换为Carbon实例。

我想扩展具有类似功能的基础模型。例如,受保护的$ times属性。所有时间属性都将转换为碳实例

你会如何做到这一点?

在此先感谢。

回答

0

这很容易,无论你想做什么。基本的PHP知识。

如果你想添加一些其他字段转换为Carbon情况下,简单地将它们添加到$dates阵列

如果你想添加一些新的参数,只是延长laravel的模型如下图所示

<?php 
namespace App; 

class MyModel extends \Illuminate\Database\Eloquent\Model 
{ 

    protected $awesomness = []; 

    /** 
    * override method 
    * 
    */ 
    public function getAttributeValue($key) 
    { 
     $value = $this->getAttributeFromArray($key); 

     // If the attribute has a get mutator, we will call that then return what 
     // it returns as the value, which is useful for transforming values on 
     // retrieval from the model to a form that is more useful for usage. 
     if ($this->hasGetMutator($key)) 
     { 
      return $this->mutateAttribute($key, $value); 
     } 

     // If the attribute exists within the cast array, we will convert it to 
     // an appropriate native PHP type dependant upon the associated value 
     // given with the key in the pair. Dayle made this comment line up. 
     if ($this->hasCast($key)) 
     { 
      return $this->castAttribute($key, $value); 
     } 

     // If the attribute is listed as a date, we will convert it to a DateTime 
     // instance on retrieval, which makes it quite convenient to work with 
     // date fields without having to create a mutator for each property. 
     if (in_array($key, $this->getDates()) && !is_null($value)) 
     { 
      return $this->asDateTime($value); 
     } 

     // 
     // 
     // that's the important part of our modification 
     // 
     // 
     if (in_array($key, $this->awesomness) && !is_null($value)) 
     { 
      return $this->doAwesomness($value); 
     } 

     return $value; 
    } 

    public function doAwesomness($value) 
    { 
     //do whatever you want here 
     return $value; 
    } 

} 

然后所有的模型只需要延长\App\MyModel类而不是\Illuminate\Database\Eloquent\Model