2016-11-23 1 views
0

In Laravel erweitern alle Modelle das Basismodell.Erweiterung Laravels Basismodell

Die Laravel eloquenten Modelle haben ein geschütztes Array-Attribut namens $ dates. Jedes Datum, das zu diesem Array hinzugefügt wird, wird automatisch in eine Carbon-Instanz konvertiert.

Ich möchte das Basismodell mit ähnlicher Funktionalität erweitern. Zum Beispiel mit einem geschützten $ times-Attribut. Alle Zeitattribute würden in eine Carbon-Instanz umgewandelt werden

Wie würden Sie das tun?

Vielen Dank im Voraus.

Antwort

0

Das ist einfach, was auch immer Sie tun möchten. Grundlegende PHP Kenntnisse.

Wenn Sie einige andere Felder hinzufügen möchten Carbon Instanzen umgewandelt werden, fügen Sie einfach, sie zu $dates Array

Wenn Sie einige neue Parameter erweitern nur hinzufügen möchten Laravel Modell wie unten

gezeigt
<?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; 
    } 

} 

Dann müssen alle Ihre Modelle nur \App\MyModel Klasse statt \Illuminate\Database\Eloquent\Model

erweitern
Verwandte Themen