PHP Basics SF - 15 04 24
PHP Basics SF - 15 04 24
for Symfony
1
OOP PHP
A. Installing an IDE
B. OOP evolution history in PHP
C. OOP in PHP and UML
D. Design Patterns
E. Testing - PHPUnit
SensioLabs 2
IDE
SensioLabs 3
IDE
SensioLabs 4
IDE
SensioLabs 5
PHP OOP
evolution
SensioLabs 6
PHP OOP history
● PHP 4 (2002)
○ Fake object model, decorated arrays
● PHP 5 (2004)
○ Real object model borrowed from Java
● PHP 7 (2015)
○ Types (non mandatory)
● PHP 8 (2020)
○ Improvements
SensioLabs 7
Side note: PSRs
SensioLabs 8
Side note: PSRs
Notable PSRs:
● PSR 1 & 12 : Basic and Extended Coding Styles
● PSR 3 : Logging Interface
● PSR 4 : Autoloading
● PSR 11 : Container Interface
● PSR 14 : Event Dispatcher
● …
Source : https://www.php-fig.org/psr/
SensioLabs 9
OOP basics
SensioLabs 10
OOP main principles
SensioLabs 11
OOP main implementations
SensioLabs 12
Procedural code
Directly answers the problem with the shortest solution
Instructions difficult to change later on
Pros :
Quick, efficient, performant
Result visible very fast
Cons :
Not changeable, not evolutive
May be hard to work together on the same code
SensioLabs 13
Object approach
SensioLabs 14
Object vs Procedural
Adding a functionality or changing existing behavior:
Procedural :
You must break your code
You must think about solutions
Object :
You just have to add more code, without breaking existing
The solution is often already found : a pattern
SensioLabs 15
Object approach
SensioLabs 16
Why use OOP ?
SensioLabs 18
Declaring and using a simple class
SensioLabs 19
A class
A class:
● Is declared using the class keyword
● Usually has a name written in PascalCase (CamelCase
with uppercase first letter)
● Contains members (properties/variables and
methods/functions) inside its curly braces
● Is the blueprint used to create an object instance
SensioLabs 20
Classes
You can declare as many classes per file as you want but
usually, to follow common conventions and PHP Standard
Recommandations (PSR) :
● One class = one file
● The filename is [ClassName].php
SensioLabs 21
A property
has a visibility :
● public : can be accessed anywhere
● private : can only be accessed into the declaring class
● protected : can be accessed into the declaring class
and every child class (inheritance)
SensioLabs 22
A property
SensioLabs 23
PHP unknown properties
PHP writes to unknown properties by creating them silently
SensioLabs 24
PHP unknown properties
Object to array and array to object cast
SensioLabs 25
A method
has a visibility :
● public : can be used anywhere
● private : can only be used into the declaring class
● protected : can be used into the declaring class and
every child class (inheritance)
SensioLabs 26
A method
SensioLabs 27
Typing things
SensioLabs 28
Special types
● mixed :
Any type (but still a declared type, same as no type
declared, but cleaner)
● void (return type only):
No return statement allowed
● never (return type only) :
function must exit() or throw an exception/trigger error
SensioLabs 29
Special types
SensioLabs 30
Several types at once
Types can be unioned
SensioLabs 31
Several types at once
Types can be intersected
SensioLabs 32
Several types at once
SensioLabs 33
Typed properties initialization
Typed attributes cannot be accessed if they are not initialized
with a default value or a constructor
SensioLabs 34
Typed properties initialization
SensioLabs 35
Null type
Null is a special type. It is a type : null
Acceptable null type may be expressed as null or with a ?
SensioLabs 36
Null type
Null is a special type. It is a type : null
Acceptable null type may be expressed as null or with a ?
SensioLabs 37
Constructor
SensioLabs 38
Constructor
SensioLabs 39
Constructor syntax
SensioLabs 40
Constructor syntax
SensioLabs 41
$this
SensioLabs 42
$this
SensioLabs 43
Destructor
● Called at the end of life of the object
● Destructors are uncommon in PHP and not very useful
● It is hard to master the order of their calls
SensioLabs 44
Practice OOP
● Create a class named Member with attributes login -
password - age
● Create a constructor to initialize those attributes to
values
● Create an auth() method receiving 2 string
parameters. It will compare them to login and
password of the object and return true if they match,
false otherwise
SensioLabs 45
OOP
advanced
concepts
SensioLabs 46
Relations : Inheritance
SensioLabs 47
Relations : Inheritance
SensioLabs 48
Liskov principle
Inheritance : any class may be replaced by one of its children
without breaking the application.
SensioLabs 49
Liskov principle
SensioLabs 50
Liskov principle
Liskov Substitution Principle leads to the principles of
Covariance and Contravariance
SensioLabs 51
Parent context
SensioLabs 52
Parent context
SensioLabs 53
Practice POO : inheritance
SensioLabs 54
Static method /property
SensioLabs 55
Static method /property
Calling convention:
● from the class itself : self::someStaticMethod()
● otherwise : MyClass::someStaticMethod()
The static accessor is double semicolon ::
● self references the current class into its own body
● static references the runtime calling class into a class body
SensioLabs 56
Static method /property
SensioLabs 57
Inheritance and static
parent:: resolves the parent scope, static or not
SensioLabs 58
Static scope resolution
self and static are similar, but the difference comes with
inheritance:
● self:: resolves the class itself (in which "self" is
written)
● static:: resolves the calling scope class at runtime
SensioLabs 59
Static scope resolution
SensioLabs 60
Class constants
Class constants:
● are declared with the const keyword
● are accessed using ::
● can only contain compile-time static values
● are allowed a visibility but are public by default
● are not allowed a type before PHP 8.3 (implicit typing)
SensioLabs 61
Class constants
SensioLabs 62
Class constants
SensioLabs 63
Practice : static and constants
SensioLabs 64
Practice : static and constants
SensioLabs 65
What is an interface ?
● Allows to store abstract behaviors (method signatures
only, no logic)
● Allows to type objects based on their behaviors
SensioLabs 66
Interfaces
SensioLabs 67
Practice : interfaces
SensioLabs 68
Abstract classes
SensioLabs 69
Abstract classes
SensioLabs 70
Abstract class practice
SensioLabs 71
Traits
SensioLabs 72
Traits example
SensioLabs 73
Exceptions
SensioLabs 74
Exceptions : error management
When an error happen in OOP usage, make use of
exception to smartly handle error cases
SensioLabs 75
Throwing an exception
The throw keyword:
● triggers an interrupt in the normal flow of execution.
● can only be followed by an object extending the Exception class
SensioLabs 76
The Exception class
SensioLabs 77
The Exception class
SensioLabs 78
Some native Exceptions
SensioLabs 79
Fatal errors
SensioLabs 80
Fatal error examples
SensioLabs 81
Fatal error examples
SensioLabs 82
Practice Exceptions
SensioLabs 83
Anonymous
functions
SensioLabs 84
Anonymous functions (closure)
An anonymous function is a nameless function internally
represented by an object from the Closure class.
You cannot create a Closure object by hand
2 syntaxes define anonymous functions
SensioLabs 85
Anonymous functions (closure)
$this into a Closure can be bound to whatever scope you
need
SensioLabs 86
Anonymous functions (closure)
You can also create
a Closure from an
existing function.
SensioLabs 87
callable pseudo-type
callable is a special type representing something that can
be invoked like a function.
● A Closure :
● A string representing a function :
● An array representing an object and a method :
● An object using __invoke() :
SensioLabs 88
callable pseudo-type
SensioLabs 89
Tools
SensioLabs 90
API for objets
● instanceof - is_a($obj, $classname)
● is_subclass_of($classOrObject, $classname)
● get_class($object)
● get_parent_class($classOrObject)
● method_exists($classOrObject, $method)
● property_exists($classOrObject, $prop)
● class_exists($class, $useAutoload)
● get_class_vars($class) - get_class_methods($class)
● get_object_vars($obj) - get_object_methods($obj)
SensioLabs 91
API for objets
You can also use the Reflection API (\Reflection class and
derivatives) or the following CLI options.
SensioLabs 92
PHP : internal classes
PHP Classes come from PHP’s libraries (SPL, PDO, Date,
SimpleXML, DOM, Mysqli …).
New classes are added regularly.
SensioLabs 93
Drawing a class
SensioLabs 94
UML Modelisation
● PlantUML
● DIA
● StarUML
● Poseidon
● Altova Umodel
● ArgoUML
● BOUML
● ...
SensioLabs 95
Relations
between
classes
SensioLabs 96
Relations between classes
UML defines relationship types :
● Inheritance
● Implementation
● Association
● Aggregation
● Composition
Other types are not used in the PHP language (only in
more complex OOP languages like Java or C++)
SensioLabs 97
Relations : Inheritance
Inheritance is a hard link : "B is a A" , "B is a kind of A"
There is no multiple inheritance in PHP
SensioLabs 98
Relations : implementation
Implementation is a hard link : "B is a A" , "B allows to do A::x"
A class can implement several interfaces
SensioLabs 99
Relations : association
Association is a deep link, and has some sub categories
It represents the usage of an object into an other
SensioLabs 100
Relations : aggregation
Aggregation is a permanent usage association where both objects can
exist independently from each other.
It’s usually implemented with set() , get() or add() and remove()
SensioLabs 101
Relations : composition
Composition is a permanent usage association in which one object
cannot exist outside of the other.
No getter or setter are created, instantiation is done into the class itself
SensioLabs 102
Namespaces
SensioLabs 103
Namespaces
SensioLabs 104
Namespaces
SensioLabs 105
Namespaces syntax
SensioLabs 106
Namespaces syntax
SensioLabs 107
Using namespaces
SensioLabs 108
Using namespaces
SensioLabs 109
Namespaces resolution
SensioLabs 110
Namespaces resolution fallback
PHP fallbacks to the global namespace, but only for functions
and constants, not for classes.
SensioLabs 111
Current namespace access
Use the namespace keyword or the __NAMESPACE__ constant to get the
current namespace.
The current namespace is resolved during script compilation. Any
dynamic runtime accesses must be resolved manually.
SensioLabs 112
Fully Qualified Class Name
SensioLabs 113
Fully Qualified Class Name
SensioLabs 114
Practice namespaces
SensioLabs 115
Autoload
SensioLabs 116
Autoloader
Autoload is a PHP feature allowing to automatically require() class files
spl_autoload_register() in PHP
We usually use Composer to generate our autoloader
SensioLabs 117
Practice autoloader
SensioLabs 118