SlideShare a Scribd company logo
ČTVRTKON
FLUENT INTERFACES
PROBLÉM SKLÁDÁNÍ FUNKCÍ A OBJEKTŮ - POSTFIX NOTACE
$json = new ParseJson(

new AssertResponseStatus(

new RequestWithHeader(

new AuthHeader('basic', $username, $password),

new RequestWithMethod(

'GET',

new Request('example.com')

)

),

200

)

).toString();
TEXT
FLUENT INTEFACE
class Request {

// ...

function withMethod($method) {

$this->method = $method;

return $this;

}

// ...

}

TEXT
FLUENT INTEFACE
$json = new Request('example.com')

->withMethod('GET')

->withHeader(new AuthHeader('basic', $username, $password))

->assertResponseStatus(200)

->parseJson()

->toString();

THE API IS PRIMARILY DESIGNED TO BE
READABLE AND TO FLOW. THE PRICE OF THIS
FLUENCY IS MORE EFFORT, BOTH IN THINKING
AND IN THE API CONSTRUCTION ITSELF.
Martin Fowler
TEXT
TEXT
NEVÝHODY FLUENT INTERFACE
‣Špatná rozšiřitelnost
‣Nemožnost spojit do "fluentu" více rozhraní
‣Proxy / dekorátory a "unwrapnutí" $this!
TEXT
UNWRAP
class FluentCounter {

$i = 0;

function inc() {

$this->i++;

return $this;

}

}



class LoggerCounter {

$this->counter = new FluentCounter();

function inc() {

echo "calling incn";

return $this->counter->inc();

}

}



new LoggerCounter(new FluentCounter())->inc()->inc()->inc(); // "calling inc" (jednou)
TEXT
UNWRAP
class FluentCounter {

$i = 0;

function inc() {

$this->i++;

return $this;

}

}



class LoggerCounter {

$this->counter = new FluentCounter();

function inc() {

echo "calling incn";

$this->counter = $this->counter->inc();

return $this;

}

}



new LoggerCounter(new FluentCounter())->inc()->inc()->inc(); // "calling inc" (třikrát)
TEXT
NEŠLO BY PROSTĚ OTOČIT POŘADÍ?
function revert2($fn1, $fn2) {

return function (...$args) use ($fn1, $fn2) {

return $fn2($fn1(...$args));

};

}
function fn1($x) {

return 'fn1(' . $x . ')';

}



function fn2($x) {

return 'fn2(' . $x . ')';

}



echo revert2('fn1', 'fn2')('x'); // 'fn2(fn1(x))'
TEXT
JAK TO UDĚLAT PRO N FUNKCÍ?
TEXT
JAK TO UDĚLAT PRO N FUNKCÍ?
function revert2($fn1, $fn2) {

return function (...$args) use ($fn1, $fn2) {

return $fn2($fn1(...$args));

};

}
function revert($f1, ...$fns) {

return array_reduce($fns, 'revert2', $f1);

}
// final version:
function revert($f1, ...$fns) {

return array_reduce($fns, function ($fn1, $fn2) {

return function (...$args) use ($fn1, $fn2) { return $fn2($fn1(...$args)); };

}, $f1);

}
REVERT = PIPE OPERÁTOR
TEXT
POUŽITÍ
$json = pipe(

new Request('example.com'),

new WithMethod('GET'),

new WithHeader(new AuthHeader('basic', $username, $password),

new AssertResponseStatus(200),

new ParseJson(),

)->toString();
// s pipe operátorem:
$json = new Request('example.com')

|> new WithMethod($$, 'GET'),

|> new WithHeader(new AuthHeader('basic', $username, $password), $$),

|> new AssertResponseStatus($$, 200),

|> new ParseJson(),

|> toString();
TEXT
PIPE OPERÁTOR V OSTATNÍCH JAZYCÍCH
▸ PHP: https://wiki.php.net/rfc/pipe-operator
▸ javascript: https://github.com/tc39/proposal-pipeline-
operator
▸ C#: https://github.com/dotnet/csharplang/issues/96
▸ ...
DÍKY ZA POZORNOST

More Related Content

PDF
TestFest - Respect\Validation 1.0
PDF
20 modules i haven't yet talked about
PDF
Pim Elshoff "Final Class Aggregate"
PDF
ODP
PHP pod mikroskopom
PDF
Advanced modulinos trial
PDF
Advanced modulinos
TestFest - Respect\Validation 1.0
20 modules i haven't yet talked about
Pim Elshoff "Final Class Aggregate"
PHP pod mikroskopom
Advanced modulinos trial
Advanced modulinos

What's hot (20)

PDF
Bag of tricks
PDF
PHP for Adults: Clean Code and Object Calisthenics
PDF
Perl Bag of Tricks - Baltimore Perl mongers
DOC
PPTX
PDF
Storytelling By Numbers
DOCX
Table through php
PDF
C A S Sample Php
PDF
Parsing JSON with a single regex
PDF
Melhorando sua API com DSLs
PDF
The Magic Of Tie
PDF
introduction to Django in five slides
PDF
You code sucks, let's fix it
PDF
Learning Perl 6 (NPW 2007)
PDF
Functional programming with php7
PDF
Learning Perl 6
PDF
Perl6 grammars
PDF
Refactoring using Codeception
PDF
Perl6 operators and metaoperators
Bag of tricks
PHP for Adults: Clean Code and Object Calisthenics
Perl Bag of Tricks - Baltimore Perl mongers
Storytelling By Numbers
Table through php
C A S Sample Php
Parsing JSON with a single regex
Melhorando sua API com DSLs
The Magic Of Tie
introduction to Django in five slides
You code sucks, let's fix it
Learning Perl 6 (NPW 2007)
Functional programming with php7
Learning Perl 6
Perl6 grammars
Refactoring using Codeception
Perl6 operators and metaoperators
Ad

Similar to DEV Čtvrtkon #76 - Fluent Interface (20)

PPTX
Jquery ajax & form
PDF
Intoduction to php restful web service
KEY
Workshop unittesting
PDF
Unit testing with zend framework tek11
KEY
Unit testing with zend framework PHPBenelux
PDF
Min-Maxing Software Costs
PDF
Silex meets SOAP & REST
PDF
Advanced php testing in action
KEY
Unit testing zend framework apps
PDF
WordPress REST API hacking
KEY
Object Calisthenics Applied to PHP
PDF
Simplify AJAX using jQuery
PPTX
Presentation1
PDF
PHP Conference Asia 2016
ODP
PHPUnit elevato alla Symfony2
PDF
WordPress REST API hacking
PDF
PhpUnit - The most unknown Parts
PDF
Leveraging Symfony2 Forms
PDF
Make WordPress realtime.
PPTX
Crafting beautiful software
Jquery ajax & form
Intoduction to php restful web service
Workshop unittesting
Unit testing with zend framework tek11
Unit testing with zend framework PHPBenelux
Min-Maxing Software Costs
Silex meets SOAP & REST
Advanced php testing in action
Unit testing zend framework apps
WordPress REST API hacking
Object Calisthenics Applied to PHP
Simplify AJAX using jQuery
Presentation1
PHP Conference Asia 2016
PHPUnit elevato alla Symfony2
WordPress REST API hacking
PhpUnit - The most unknown Parts
Leveraging Symfony2 Forms
Make WordPress realtime.
Crafting beautiful software
Ad

More from Ctvrtkoncz (16)

PDF
DEV Čtvrtkon #107 - Štefan Földesi
PPTX
#85 Čtvrtkon - Obsahové UX - Milan Pichlík
PDF
DEV Čtvrtkon #76 - Open API
PDF
DEV Čtvrtkon #76 - Makefile
PDF
DEV Čtvrtkon #76 - nopCommerce
PDF
DEV Čtvrtkon #76 - Nachytřená domácnost
PDF
DEV Čtvrtkon #76 - How to build an evil-free social network: Behind the wheels
PDF
Čtvrtkon: Podle jakých kritérií vybrat e-shopové řešení
PDF
Čtvrtkon #71 - Jan Kaštánek - Java & Docker & Microsevices
PPTX
Čtvrtkon #71 - Marian Benčat - Angular a NativeScript
PDF
Čtvrtkon #64 - AWS Serverless - Michal Haták
PDF
Jak nakrmit Facebook firemní stránku a Instagram obsahem, co její fanoušci do...
PDF
Pravdy a lži o reklamě na Facebooku - Lukáš Chládek
PDF
Vilibald Wanča - Api design-lifecycle
ODP
Jan Kaštánek - Od webových aplikací k Androidu
PPTX
Propagace eshopu v praxi - Čtvrtkon
DEV Čtvrtkon #107 - Štefan Földesi
#85 Čtvrtkon - Obsahové UX - Milan Pichlík
DEV Čtvrtkon #76 - Open API
DEV Čtvrtkon #76 - Makefile
DEV Čtvrtkon #76 - nopCommerce
DEV Čtvrtkon #76 - Nachytřená domácnost
DEV Čtvrtkon #76 - How to build an evil-free social network: Behind the wheels
Čtvrtkon: Podle jakých kritérií vybrat e-shopové řešení
Čtvrtkon #71 - Jan Kaštánek - Java & Docker & Microsevices
Čtvrtkon #71 - Marian Benčat - Angular a NativeScript
Čtvrtkon #64 - AWS Serverless - Michal Haták
Jak nakrmit Facebook firemní stránku a Instagram obsahem, co její fanoušci do...
Pravdy a lži o reklamě na Facebooku - Lukáš Chládek
Vilibald Wanča - Api design-lifecycle
Jan Kaštánek - Od webových aplikací k Androidu
Propagace eshopu v praxi - Čtvrtkon

Recently uploaded (20)

PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PPTX
E -tech empowerment technologies PowerPoint
PPTX
PptxGenJS_Demo_Chart_20250317130215833.pptx
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
PPTX
newyork.pptxirantrafgshenepalchinachinane
PPTX
Introduction to Information and Communication Technology
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PDF
Introduction to the IoT system, how the IoT system works
PPTX
international classification of diseases ICD-10 review PPT.pptx
DOCX
Unit-3 cyber security network security of internet system
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
PPT
Ethics in Information System - Management Information System
PDF
Sims 4 Historia para lo sims 4 para jugar
PPTX
artificial intelligence overview of it and more
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
Funds Management Learning Material for Beg
Slides PDF The World Game (s) Eco Economic Epochs.pdf
Slides PPTX World Game (s) Eco Economic Epochs.pptx
E -tech empowerment technologies PowerPoint
PptxGenJS_Demo_Chart_20250317130215833.pptx
SASE Traffic Flow - ZTNA Connector-1.pdf
Power Point - Lesson 3_2.pptx grad school presentation
newyork.pptxirantrafgshenepalchinachinane
Introduction to Information and Communication Technology
INTERNET------BASICS-------UPDATED PPT PRESENTATION
Introduction to the IoT system, how the IoT system works
international classification of diseases ICD-10 review PPT.pptx
Unit-3 cyber security network security of internet system
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
Ethics in Information System - Management Information System
Sims 4 Historia para lo sims 4 para jugar
artificial intelligence overview of it and more
Design_with_Watersergyerge45hrbgre4top (1).ppt
Decoding a Decade: 10 Years of Applied CTI Discipline
Module 1 - Cyber Law and Ethics 101.pptx
Funds Management Learning Material for Beg

DEV Čtvrtkon #76 - Fluent Interface

  • 2. PROBLÉM SKLÁDÁNÍ FUNKCÍ A OBJEKTŮ - POSTFIX NOTACE $json = new ParseJson(
 new AssertResponseStatus(
 new RequestWithHeader(
 new AuthHeader('basic', $username, $password),
 new RequestWithMethod(
 'GET',
 new Request('example.com')
 )
 ),
 200
 )
 ).toString();
  • 3. TEXT FLUENT INTEFACE class Request {
 // ...
 function withMethod($method) {
 $this->method = $method;
 return $this;
 }
 // ...
 }

  • 4. TEXT FLUENT INTEFACE $json = new Request('example.com')
 ->withMethod('GET')
 ->withHeader(new AuthHeader('basic', $username, $password))
 ->assertResponseStatus(200)
 ->parseJson()
 ->toString();

  • 5. THE API IS PRIMARILY DESIGNED TO BE READABLE AND TO FLOW. THE PRICE OF THIS FLUENCY IS MORE EFFORT, BOTH IN THINKING AND IN THE API CONSTRUCTION ITSELF. Martin Fowler TEXT
  • 6. TEXT NEVÝHODY FLUENT INTERFACE ‣Špatná rozšiřitelnost ‣Nemožnost spojit do "fluentu" více rozhraní ‣Proxy / dekorátory a "unwrapnutí" $this!
  • 7. TEXT UNWRAP class FluentCounter {
 $i = 0;
 function inc() {
 $this->i++;
 return $this;
 }
 }
 
 class LoggerCounter {
 $this->counter = new FluentCounter();
 function inc() {
 echo "calling incn";
 return $this->counter->inc();
 }
 }
 
 new LoggerCounter(new FluentCounter())->inc()->inc()->inc(); // "calling inc" (jednou)
  • 8. TEXT UNWRAP class FluentCounter {
 $i = 0;
 function inc() {
 $this->i++;
 return $this;
 }
 }
 
 class LoggerCounter {
 $this->counter = new FluentCounter();
 function inc() {
 echo "calling incn";
 $this->counter = $this->counter->inc();
 return $this;
 }
 }
 
 new LoggerCounter(new FluentCounter())->inc()->inc()->inc(); // "calling inc" (třikrát)
  • 9. TEXT NEŠLO BY PROSTĚ OTOČIT POŘADÍ? function revert2($fn1, $fn2) {
 return function (...$args) use ($fn1, $fn2) {
 return $fn2($fn1(...$args));
 };
 } function fn1($x) {
 return 'fn1(' . $x . ')';
 }
 
 function fn2($x) {
 return 'fn2(' . $x . ')';
 }
 
 echo revert2('fn1', 'fn2')('x'); // 'fn2(fn1(x))'
  • 10. TEXT JAK TO UDĚLAT PRO N FUNKCÍ?
  • 11. TEXT JAK TO UDĚLAT PRO N FUNKCÍ? function revert2($fn1, $fn2) {
 return function (...$args) use ($fn1, $fn2) {
 return $fn2($fn1(...$args));
 };
 } function revert($f1, ...$fns) {
 return array_reduce($fns, 'revert2', $f1);
 } // final version: function revert($f1, ...$fns) {
 return array_reduce($fns, function ($fn1, $fn2) {
 return function (...$args) use ($fn1, $fn2) { return $fn2($fn1(...$args)); };
 }, $f1);
 }
  • 12. REVERT = PIPE OPERÁTOR
  • 13. TEXT POUŽITÍ $json = pipe(
 new Request('example.com'),
 new WithMethod('GET'),
 new WithHeader(new AuthHeader('basic', $username, $password),
 new AssertResponseStatus(200),
 new ParseJson(),
 )->toString(); // s pipe operátorem: $json = new Request('example.com')
 |> new WithMethod($$, 'GET'),
 |> new WithHeader(new AuthHeader('basic', $username, $password), $$),
 |> new AssertResponseStatus($$, 200),
 |> new ParseJson(),
 |> toString();
  • 14. TEXT PIPE OPERÁTOR V OSTATNÍCH JAZYCÍCH ▸ PHP: https://wiki.php.net/rfc/pipe-operator ▸ javascript: https://github.com/tc39/proposal-pipeline- operator ▸ C#: https://github.com/dotnet/csharplang/issues/96 ▸ ...