I Traits permettono di riutilizzare codice in classi non correlate.
Definire un Trait
trait Timestampable {
public $createdAt;
public $updatedAt;
public function setCreatedAt() {
$this->createdAt = new DateTime();
}
public function setUpdatedAt() {
$this->updatedAt = new DateTime();
}
}Usare Trait
class Post {
use Timestampable;
public $title;
}
class Comment {
use Timestampable;
public $content;
}
$post = new Post();
$post->setCreatedAt();Multipli Traits
class User {
use Timestampable, Loggable, Notifiable;
}