SlideShare a Scribd company logo
Effective PHP. Outlook
● Creating objects
● Methods common to all objects
● Classes and interfaces
● Methods
● General programming
● Exceptions & logging
Effective PHPVasily Kartashov
notes.kartashov.com
Session 1:
Creating Objects
Consider static factory method
instead of constructors.
Two things are bad about default PHP constructor
● PHP doesn’t allow overloaded function signatures, as in using same
method name with different arguments
● “new” operator has lower precedence than “->”
Typical solution #1:
Merged signature
public function __construct(string $type, string $content)
{
if ($type == 'text') {
$this->type = $type;
$this->text = $content;
} elseif ($type == 'ssml') {
...
} else {
throw new IllegalArgumentException(...);
}
}
Typical solution #1:
Obscure arrays of parameters
public function __construct(array $options)
{
if ($options['type'] == 'text') {
$this->type = $options['type'];
$this->text = $options['text'];
} elseif ($options['type'] == 'ssml') {
...
} else {
throw new IllegalArgumentException(...);
}
}
Static factory methods:
class SpeechOuptut {
Private $text, $type;
private function __construct() {}
public static function plainText(string $text) {
$speech = new self;
$speech->type = 'text';
$speech->text = $text;
return $speech;
}
public static function ssml(string $ssml) {
...
}
}
Pros & Cons
➔ Static factories are harder to chain.
Subclasses may need to redefine all
the factory methods
➔ Static factories are clearer
➔ Static factories avoid ambiguous and
irrelevant parameters
Enforce singleton with a static
property:
public static function database(): Database
{
static $database;
if (!isset($database)) {
$database = new Database();
}
return $database;
}
Pros & Cons
➔ Singletons are efficient
➔ Some algorithms require singletons,
like types in GraphQL schema
➔ Singletons can be super dangerous
when they contain state, use with
care
Enforce non-instantiability with a
private constructor:
class Helper
{
private __constructor() {}
public static function randomName(): string
{
...
}
}
Pros & Cons
➔ It’s communicates perfectly clear the
intention of the class and how it
should be used
➔ Good solution if you want to use free
standing methods with autoloading
Builder pattern:
class ControllerProgram
{
private __constructor() {}
public static function builder(): ControllerProgramBuilder
{
$program = new ControllerProgram;
$constructor = function (array $zones) use ($program) {
$program->zones = $zones;
return $program;
}
return new ControllerProgramBuilder($constructor);
}
}
Builder pattern. Builder:
class ControllerProgramBuilder
{
private $constructor;
private $zones;
public function __construct(callable $constructor) {
$this->constructor = $constructor;
}
public function withZones(array $zones): ControllerProgramBuilder {
foreach ($zones as $zone) assert ($zone instanceof Zone::class);
$this->zones = $zones;
return $this;
}
public function build(): ControllerProgram {
return ($this->constructor)($this->zones);
}
}
Pros & Cons
➔ Quite complex
➔ The builder and the class itself
contain pretty much the same
information
➔ Much easier to test validity of
arguments
➔ Prevents user from creating
misformed objects, and provides nice
chaining way of creating objects

More Related Content

What's hot

Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
Jalpesh Vasa
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Object oriented php
Object oriented phpObject oriented php
Object oriented phpjwperry
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Dhruvin Shah
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
Svetlin Nakov
 
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
tumetr1
 
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
Alexander Varwijk
 
Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)
Nikos Kalogridis
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Dr Sukhpal Singh Gill
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
WebStackAcademy
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
Broadleaf Commerce
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
Md. Imran Hossain Showrov
 
Data types in php
Data types in phpData types in php
Data types in phpilakkiya
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScript
ldaws
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
anshu_atri
 

What's hot (19)

Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Object oriented php
Object oriented phpObject oriented php
Object oriented php
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Javascript
JavascriptJavascript
Javascript
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
 
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
 
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
 
Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
Os Welton
Os WeltonOs Welton
Os Welton
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Data types in php
Data types in phpData types in php
Data types in php
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScript
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 

Similar to Effective PHP. Part 1

Design Patterns and Usage
Design Patterns and UsageDesign Patterns and Usage
Design Patterns and Usage
Mindfire Solutions
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
go_oh
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
Fwdays
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
GeorgePeterBanyard
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
guest4d57e6
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
Divante
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
Tricode (part of Dept)
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
Pavel Makhrinsky
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"
Fwdays
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
Jonathan Felch
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
LogeekNightUkraine
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
Lars Jankowfsky
 

Similar to Effective PHP. Part 1 (20)

Design Patterns and Usage
Design Patterns and UsageDesign Patterns and Usage
Design Patterns and Usage
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
OOP
OOPOOP
OOP
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 

Recently uploaded

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 

Effective PHP. Part 1

  • 1. Effective PHP. Outlook ● Creating objects ● Methods common to all objects ● Classes and interfaces ● Methods ● General programming ● Exceptions & logging
  • 3. Consider static factory method instead of constructors. Two things are bad about default PHP constructor ● PHP doesn’t allow overloaded function signatures, as in using same method name with different arguments ● “new” operator has lower precedence than “->”
  • 4. Typical solution #1: Merged signature public function __construct(string $type, string $content) { if ($type == 'text') { $this->type = $type; $this->text = $content; } elseif ($type == 'ssml') { ... } else { throw new IllegalArgumentException(...); } }
  • 5. Typical solution #1: Obscure arrays of parameters public function __construct(array $options) { if ($options['type'] == 'text') { $this->type = $options['type']; $this->text = $options['text']; } elseif ($options['type'] == 'ssml') { ... } else { throw new IllegalArgumentException(...); } }
  • 6. Static factory methods: class SpeechOuptut { Private $text, $type; private function __construct() {} public static function plainText(string $text) { $speech = new self; $speech->type = 'text'; $speech->text = $text; return $speech; } public static function ssml(string $ssml) { ... } }
  • 7. Pros & Cons ➔ Static factories are harder to chain. Subclasses may need to redefine all the factory methods ➔ Static factories are clearer ➔ Static factories avoid ambiguous and irrelevant parameters
  • 8. Enforce singleton with a static property: public static function database(): Database { static $database; if (!isset($database)) { $database = new Database(); } return $database; }
  • 9. Pros & Cons ➔ Singletons are efficient ➔ Some algorithms require singletons, like types in GraphQL schema ➔ Singletons can be super dangerous when they contain state, use with care
  • 10. Enforce non-instantiability with a private constructor: class Helper { private __constructor() {} public static function randomName(): string { ... } }
  • 11. Pros & Cons ➔ It’s communicates perfectly clear the intention of the class and how it should be used ➔ Good solution if you want to use free standing methods with autoloading
  • 12. Builder pattern: class ControllerProgram { private __constructor() {} public static function builder(): ControllerProgramBuilder { $program = new ControllerProgram; $constructor = function (array $zones) use ($program) { $program->zones = $zones; return $program; } return new ControllerProgramBuilder($constructor); } }
  • 13. Builder pattern. Builder: class ControllerProgramBuilder { private $constructor; private $zones; public function __construct(callable $constructor) { $this->constructor = $constructor; } public function withZones(array $zones): ControllerProgramBuilder { foreach ($zones as $zone) assert ($zone instanceof Zone::class); $this->zones = $zones; return $this; } public function build(): ControllerProgram { return ($this->constructor)($this->zones); } }
  • 14. Pros & Cons ➔ Quite complex ➔ The builder and the class itself contain pretty much the same information ➔ Much easier to test validity of arguments ➔ Prevents user from creating misformed objects, and provides nice chaining way of creating objects