SlideShare a Scribd company logo
1 of 12
Download to read offline
Effective PHPVasily Kartashov
notes.kartashov.com
Session 4:
Classes and Interfaces. Cont’d
Design for inheritance or prohibit it
Real world example:
class FilesystemLogger implements LoggerInterface
{
...
private function validatePath(string $path): bool {
return preg_match(‘|^[a-z0-9]$|’, $path);
}
...
}
You cannot update validator, but you can extend the class. Either make the class final of make
validatePath protected.
Pros & Cons
➔ Not enforced by any standard or static
analyser.
➔ Communicates clearly the intent and
design of the class.
Prefer interfaces to abstract classes
Abstract classes allow you to create “half-finished” implementations, i.e. if you try and
extend an abstract class you’ll be forced to implement missing functionalities (abstract
methods) and thus comply with authors design intention. An example:
abstract class AbstractApplication {
abstract public function process(Request $request): Response;
}
You cannot create an Application without providing specific algorithm for how requests
are transformed into responses. Everything around it including autoloading, cacheing,
etc… has been defined in the AbstractApplication and we’re just missing this one bit.
Abstract classes
It’s a nice way to separate application-specific features from common features shared
between all applications. AbstractApplication contains common code, application
specific features end in the subclass of AbstractApplication.
In this case AbstractApplication and specific Application extends AbstractApplication
share the same interface, as expose the same set of public functions to outsiders.
Interfaces
Let’s say we want to write a command line runner that would accept request and
output the response to CLI.
class CliRunner {
private $implementation;
public function __construct(? $implementation) {
$this->implementation = $implementation;
}
public function run() {
$response = $this->implementation->process($request);
echo $response;
}
}
Should we use Application as $implementation type?
Pros & Cons
➔ Extracting interfaces mean increasing
number of classes. Some people see it
as “verbosity” instead of seeing it as a
process of discovering underlying
abstractions.
➔ Easier to test, to reason, harder to
abuse.
Prefer hierarchies over tagged classes
What is a tagged class?
class CompatiblityPolicy {
private $version;
public function canUpdateSoftware(): bool {
if ($this->version) {
return $this->version->software() > 125;
} else {
return false;
}
}
}
Pros & Cons
➔ Logic of tagged classes can become
quite complex quickly, imagine 2 tags
sharing 90% of the logic?
➔ As before, more classes.
Use function objects for strategies
Let’s assume we want a transactional context around our DB
queries. The typical pseudo-code would look like following
try {
start();
// your code
commit();
} catch (Exception e) {
rollback();
throw e;
}
Strategy “object”
How do we reuse “wrapping” code without copy and paste? By
passing a callback into the generic method.
try {
start();
$value = $callback();
commit();
return $value;
} catch (Exception e) {
rollback();
throw e;
}
Pros & Cons
➔ Callbacks are not typed in PHP (yet, but
there are RFCs).
➔ Easy to abuse.

More Related Content

What's hot

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelJonathan Behr
 
Object oriented php
Object oriented phpObject oriented php
Object oriented phpjwperry
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmersAlexander Varwijk
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in functiontumetr1
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional StatementsMarlon Jamera
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoringYuriy Gerasimov
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.netMethods of debugging - Atomate.net
Methods of debugging - Atomate.netVitalie Chiperi
 
Data types in php
Data types in phpData types in php
Data types in phpilakkiya
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in phpAshish Chamoli
 
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章Jumpei Yokota
 
Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)Ovidiu Farauanu
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4Yi-Huan Chan
 

What's hot (19)

Pointers & functions
Pointers &  functionsPointers &  functions
Pointers & functions
 
Java script basic
Java script basicJava script basic
Java script basic
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in Laravel
 
Object oriented php
Object oriented phpObject oriented php
Object oriented php
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
Javascript
JavascriptJavascript
Javascript
 
Os Welton
Os WeltonOs Welton
Os Welton
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in function
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoring
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.netMethods of debugging - Atomate.net
Methods of debugging - Atomate.net
 
Data types in php
Data types in phpData types in php
Data types in php
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in php
 
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章
 
Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
 

Similar to Effective PHP. Part 4

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpAlena Holligan
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Alena Holligan
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingPurvik Rana
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asmaAbdullahJana
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsChris Tankersley
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 

Similar to Effective PHP. Part 4 (20)

Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
 
Only oop
Only oopOnly oop
Only oop
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
 
Java 06
Java 06Java 06
Java 06
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 

Recently uploaded

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 

Recently uploaded (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 

Effective PHP. Part 4

  • 1. Effective PHPVasily Kartashov notes.kartashov.com Session 4: Classes and Interfaces. Cont’d
  • 2. Design for inheritance or prohibit it Real world example: class FilesystemLogger implements LoggerInterface { ... private function validatePath(string $path): bool { return preg_match(‘|^[a-z0-9]$|’, $path); } ... } You cannot update validator, but you can extend the class. Either make the class final of make validatePath protected.
  • 3. Pros & Cons ➔ Not enforced by any standard or static analyser. ➔ Communicates clearly the intent and design of the class.
  • 4. Prefer interfaces to abstract classes Abstract classes allow you to create “half-finished” implementations, i.e. if you try and extend an abstract class you’ll be forced to implement missing functionalities (abstract methods) and thus comply with authors design intention. An example: abstract class AbstractApplication { abstract public function process(Request $request): Response; } You cannot create an Application without providing specific algorithm for how requests are transformed into responses. Everything around it including autoloading, cacheing, etc… has been defined in the AbstractApplication and we’re just missing this one bit.
  • 5. Abstract classes It’s a nice way to separate application-specific features from common features shared between all applications. AbstractApplication contains common code, application specific features end in the subclass of AbstractApplication. In this case AbstractApplication and specific Application extends AbstractApplication share the same interface, as expose the same set of public functions to outsiders.
  • 6. Interfaces Let’s say we want to write a command line runner that would accept request and output the response to CLI. class CliRunner { private $implementation; public function __construct(? $implementation) { $this->implementation = $implementation; } public function run() { $response = $this->implementation->process($request); echo $response; } } Should we use Application as $implementation type?
  • 7. Pros & Cons ➔ Extracting interfaces mean increasing number of classes. Some people see it as “verbosity” instead of seeing it as a process of discovering underlying abstractions. ➔ Easier to test, to reason, harder to abuse.
  • 8. Prefer hierarchies over tagged classes What is a tagged class? class CompatiblityPolicy { private $version; public function canUpdateSoftware(): bool { if ($this->version) { return $this->version->software() > 125; } else { return false; } } }
  • 9. Pros & Cons ➔ Logic of tagged classes can become quite complex quickly, imagine 2 tags sharing 90% of the logic? ➔ As before, more classes.
  • 10. Use function objects for strategies Let’s assume we want a transactional context around our DB queries. The typical pseudo-code would look like following try { start(); // your code commit(); } catch (Exception e) { rollback(); throw e; }
  • 11. Strategy “object” How do we reuse “wrapping” code without copy and paste? By passing a callback into the generic method. try { start(); $value = $callback(); commit(); return $value; } catch (Exception e) { rollback(); throw e; }
  • 12. Pros & Cons ➔ Callbacks are not typed in PHP (yet, but there are RFCs). ➔ Easy to abuse.