Laravel5.4 ORM + PHP Traits

ORMにfunctionを追記出来るがreusableでなく、肥大化することがあるためtraitsを使うことがある。

TraitsやORMのfunctionはmethod chainやORM向けのmethodを使用できる点で優れる。

 

@App\foo.php (ORM)

use App\Traits\Friendable;

 

class User extends Authenticatable
{

  use Notifiable;

  use Friendable;

 

 

@App\Traits\Friendable.php

<php?

namespace App\Traits;

 

trait friendable {

  public function hello {
    return "Hello World!";

   }

}

 

@web.php

Rotue::get('/hello', function() {

  return Auth::user()->hello();

}); 

 

kati #9

 

参考:

monteecristoo.hatenablog.com

blog.toshimaru.net