Fluent interface in PHP | chaining methods | zəncirvari axıcı interfeys | builder pattern #kody_az

PHP

Dərs haqqında

PHP-də fluent interface (axıcı interfeys) o deməkdir ki, metodlar öz obyektini ($this) geri qaytarır və bu sayədə metodlar zəncirvari şəkildə çağırıla bilir. Məsələn, $user→setName('Hafiz')→setAge(25)→save(); yazılışı bir neçə sətrlik kodu bir sətrdə ifadə etməyə imkan verir. Bu üslub kodu həm oxunaqlı, həm də daha qısa edir. Fluent interface əsasən OOP-də (obyekt yönümlü proqramlaşdırmada) istifadə olunur və xüsusilə Laravel, Doctrine kimi framework-lərdə geniş tətbiq tapıb.

Bu yanaşmada hər metodun sonunda return $this; yazılır ki, obyekt özünü geri qaytarsın və növbəti metod eyni obyekt üzərində işləyə bilsin. Çox vaxt bu üslub Builder pattern (qurucu nümunə) ilə birlikdə istifadə olunur – yəni obyekt addım-addım qurulur və sonda build() və ya save() kimi metodla tamamlanır.

Fluent interface kodu daha təmiz və anlaşıqlı edir, amma bəzən səhvlərin tapılmasını çətinləşdirə bilər, xüsusilə metodlar fərqli tipdə dəyərlər qaytaranda. Buna görə də bu üsul daha çox obyektin konfiqurasiyası, sorğu qurucuları və ya məlumatın mərhələli emalı üçün uyğundur. Ümumilikdə, fluent interface PHP koduna daha təbii, “danışıq kimi” bir axıcılıq verir və müasir OOP dizaynının vacib hissəsidir.

======

In PHP, fluent interfaces are a programming style where methods return the same object ($this) to allow chained method calls. Instead of calling each method separately, you can link them in one line, which makes code cleaner and more expressive. For example, $user→setName('Hafiz')→setAge(25)→save(); is easier to read than writing each call on a separate line. This style is commonly used in frameworks like Laravel and Doctrine, especially in query builders and configuration classes.

Fluent interfaces depend on returning $this inside class methods, so the same object continues to be used across the chain. This technique is often combined with the builder pattern, where an object is gradually configured before being finalized with a method like build() or save(). It improves readability and reduces boilerplate by turning a sequence of steps into a single expression.

However, fluent interfaces should be used carefully—if methods return different types or perform side effects, chaining can make debugging harder. In most cases, it’s ideal for object configuration, query construction, or pipelines of transformations. Overall, fluent interfaces make PHP code feel more natural, almost like speaking a sentence, and are a key feature of modern object-oriented PHP design.

#kody_az #kodyaz #php #phpcode #laravel #phpprogramming #viral #viralcode #viralvideo #random #code #coder #azerbaycan #azerbaijan #baku #baki #programming #programmer #codes #hazırlıq #hazirliq #kurs #kurslar #course #courses #online #onlinecourses #test #quiz

YouTube-da bax · KODY.AZ