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

PDF
Effective PHP. Part 2
PDF
Effective PHP. Part 5
PDF
Effective PHP. Part 4
PDF
Effective PHP. Part 3
PDF
Effective PHP. Part 6
PPSX
Javascript variables and datatypes
PDF
DIG1108 Lesson 6
PDF
Pointers & functions
Effective PHP. Part 2
Effective PHP. Part 5
Effective PHP. Part 4
Effective PHP. Part 3
Effective PHP. Part 6
Javascript variables and datatypes
DIG1108 Lesson 6
Pointers & functions

What's hot (19)

PDF
Object Oriented PHP - PART-1
PDF
Object Oriented PHP - PART-2
PDF
JavaScript: Variables and Functions
PDF
JavaScript - Chapter 4 - Types and Statements
PPTX
Object oriented php
PPTX
Advanced Javascript
PPT
Javascript
PPTX
Dev Concepts: Functional Programming
PPT
php 2 Function creating, calling, PHP built-in function
PDF
Drupaljam xl 2019 presentation multilingualism makes better programmers
PDF
Functional programing in Javascript (lite intro)
PDF
Constructors and Destructors
PDF
JavaScript - Chapter 5 - Operators
ODP
Os Welton
PDF
Broadleaf Presents Thymeleaf
PPT
Lecture 13 - Storage Classes
PPTX
Data types in php
PDF
Practical TypeScript
PPT
Generic programming in java
Object Oriented PHP - PART-1
Object Oriented PHP - PART-2
JavaScript: Variables and Functions
JavaScript - Chapter 4 - Types and Statements
Object oriented php
Advanced Javascript
Javascript
Dev Concepts: Functional Programming
php 2 Function creating, calling, PHP built-in function
Drupaljam xl 2019 presentation multilingualism makes better programmers
Functional programing in Javascript (lite intro)
Constructors and Destructors
JavaScript - Chapter 5 - Operators
Os Welton
Broadleaf Presents Thymeleaf
Lecture 13 - Storage Classes
Data types in php
Practical TypeScript
Generic programming in java
Ad

Similar to Effective PHP. Part 1 (20)

PPT
Design Patterns and Usage
PDF
Singletons in PHP - Why they are bad and how you can eliminate them from your...
PDF
10 PHP Design Patterns #burningkeyboards
PPTX
Constructors and Destructors
PDF
Nikita Popov "What’s new in PHP 8.0?"
PDF
What's new in PHP 8.0?
PDF
PHP 8: Process & Fixing Insanity
PDF
Functional Javascript
PDF
Design patterns in PHP
PDF
Why is crud a bad idea - focus on real scenarios
PPT
Zend framework 03 - singleton factory data mapper caching logging
PDF
Building Testable PHP Applications
PPTX
Drupal 8 migrate!
PDF
Alexander Makarov "Let’s talk about code"
PDF
Groovy On Trading Desk (2010)
PDF
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
PDF
Kotlin Developer Starter in Android projects
PPT
Object Oriented Programming Concept.Hello
PPT
Design Patterns and Usage
Singletons in PHP - Why they are bad and how you can eliminate them from your...
10 PHP Design Patterns #burningkeyboards
Constructors and Destructors
Nikita Popov "What’s new in PHP 8.0?"
What's new in PHP 8.0?
PHP 8: Process & Fixing Insanity
Functional Javascript
Design patterns in PHP
Why is crud a bad idea - focus on real scenarios
Zend framework 03 - singleton factory data mapper caching logging
Building Testable PHP Applications
Drupal 8 migrate!
Alexander Makarov "Let’s talk about code"
Groovy On Trading Desk (2010)
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 projects
Object Oriented Programming Concept.Hello
Ad

Recently uploaded (20)

PPTX
Computer Hardware tool: hand tools, diagnostics, ESD and cleaning tools
PDF
Community & News Update Q2 Meet Up 2025
PPTX
Dynamic Solutions Project Pitch Presentation
PPTX
Save Business Costs with CRM Software for Insurance Agents
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
PPTX
Presentation of Computer CLASS 2 .pptx
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Benefits of DCCM for Genesys Contact Center
PDF
Become an Agentblazer Champion Challenge
PPTX
10 Hidden App Development Costs That Can Sink Your Startup.pptx
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Exploring AI Agents in Process Industries
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
Convert Thunderbird to Outlook into bulk
PDF
How to Confidently Manage Project Budgets
PDF
Comprehensive Salesforce Implementation Services.pdf
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PDF
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
Computer Hardware tool: hand tools, diagnostics, ESD and cleaning tools
Community & News Update Q2 Meet Up 2025
Dynamic Solutions Project Pitch Presentation
Save Business Costs with CRM Software for Insurance Agents
Micromaid: A simple Mermaid-like chart generator for Pharo
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Presentation of Computer CLASS 2 .pptx
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PTS Company Brochure 2025 (1).pdf.......
Benefits of DCCM for Genesys Contact Center
Become an Agentblazer Champion Challenge
10 Hidden App Development Costs That Can Sink Your Startup.pptx
How Creative Agencies Leverage Project Management Software.pdf
Exploring AI Agents in Process Industries
Become an Agentblazer Champion Challenge Kickoff
Convert Thunderbird to Outlook into bulk
How to Confidently Manage Project Budgets
Comprehensive Salesforce Implementation Services.pdf
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...

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