Fluent Interface Nedir ve Nasıl Kullanılır?

Fluent Interface Nedir ve Nasıl Kullanılır?

Tanım

  • Fluent Interface, "daha okunabilir" kod yapısı sağlayan tasarım yapısıdır (design pattern).
  • Buradaki amacımız, "class" içersinde yer alan fonksiyonları zincirlemeye yöntemiyle birbirlerine "this" ile oluşturulan nesneyi döndürerek bağlamaktır.

PHP programlama dilinde Fluent Interface kullanımı

$human->born()->eat()->sleep()->code()->die();

Normal kullanımı

$human->born();
$human->eat();
$human->sleep();
$human->code();
$human->die();

PHP'de örnek olarak oluşturulan Class

class Insan{
  private $_ad;
  private $_cinsiyet;
  private $_yas;
  private $_boy;
  private $_agirlik;

  public function ad($ad){
    $this->_ad = $ad;
    return $this;
  }

  public function cinsiyet($cinsiyet){
    $this->_cinsiyet = $cinsiyet;
    return $this;
  }

  public function yas($yas){
    $this->_yas = $yas;
    return $this;
  }

  public function boy($boy){
    $this->_boy = $boy;
    return $this;
  }

  public function agirlik($agirlik){
    $this->_agirlik= $agirlik;
    return $this;
  }

  public function kaydet(){
    $properties = get_object_vars($this);
    $str = '';
    foreach($properties as $property){
        $str .= $property.' ';
    }
    return $str;
  }
}

Oluşturduğumuz Person class Fluent Interface kullanımı;

$p = new Insan();
$res = $p->ad('Ece')->cinsiyet('Kadin')->yas('30')->boy('5.8')->agirlik('51')->kaydet();