PHPのトレイトは、複数のLivewireコンポーネント間で機能を再利用するための優れた方法です。
たとえば、アプリケーションに複数の"data table"コンポーネントがあり、それらはすべて並べ替えの同じロジックを共有している場合があります。
すべてのコンポーネントで、以下のような並べ替え定型文を複製したくはないでしょう。
class ShowPosts extends Component
{
public $sortBy = '';
public $sortDirection = 'asc';
public function sortBy($field)
{
$this->sortDirection = $this->sortBy === $field
? $this->reverseSort()
: 'asc';
$this->sortBy = $field;
}
public function reverseSort()
{
return $this->sortDirection === 'asc'
? 'desc'
: 'asc';
}
...
}
代わりに、この動作をWithSorting
と言う名前の再利用可能なトレイトに抽出できます。
class ShowPosts extends Component
{
use WithSorting;
...
}
trait WithSorting
{
public $sortBy = '';
public $sortDirection = 'asc';
public function sortBy($field)
{
$this->sortDirection = $this->sortBy === $field
? $this->reverseSort();
: 'asc';
$this->sortBy = $field;
}
public function reverseSort()
{
return $this->sortDirection === 'asc'
? 'desc'
: 'asc';
}
}
さらに、トレイト内でLivewireのライフサイクルフックを使用したいが、コンポーネント内でそれらを使用できるようにしたい場合、Livewireはこれを可能にする構文を提供します。
trait WithSorting
{
...
public function mountWithSorting()
{
//
}
public function updatingWithSorting($name, $value)
{
//
}
public function updatedWithSorting($name, $value)
{
//
}
public function hydrateWithSorting()
{
//
}
public function dehydrateWithSorting()
{
//
}
public function renderingWithSorting()
{
//
}
public function renderedWithSorting($view)
{
//
}
}