0% found this document useful (0 votes)
44 views118 pages

PHP Basics SF - 15 04 24

Uploaded by

JM Tanau
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views118 pages

PHP Basics SF - 15 04 24

Uploaded by

JM Tanau
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

PHP Basics

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

An Integrated Development Environment (IDE) is a software


allowing you to write code with many tools and capabilities
beyond that of a simple text editor.
An IDE usually provides code completion facilities, code
navigation, debugging tools, and much more.

SensioLabs 4
IDE

● You may use whichever you want :


○ PHPStorm
○ Eclipse PDT
○ VisualStudio Code
○ Netbeans
● As an alternative : SublimeText

● PHPStorm is the most advanced/powerful

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

PSRs (PHP Standard Recommandations) are a set of


guidelines edited by the PHP-FIG (PHP Framework
Interoperability Group).
Their purpose is to describe best practices in terms of code
styling or code architecture in PHP.
You are strongly encouraged to follow these 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

● Classes & Objects that send messages between each


other
● Encapsulation
● Inheritance
● Polymorphism
● Strong typing

SensioLabs 11
OOP main implementations

● Design patterns & MVC architecture


● Frameworks
● Event programming
● Software Engineering Tools

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

● Allows high reusability of code


● Allows to abstract behaviors
● Allows team work

● Allows specifications to change and follow their change


● Allows application modelisation through schemas (UML)

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

Data and treatments grouped into the same entity : a class


● Encapsulation
● Behaviors abstraction through interfaces
● Each instance is unique
● Inheritance (general - specific)
● Polymorphism

SensioLabs 16
Why use OOP ?

● Allows to modelize and order ideas


● Allows to group code at the same place (classes)

● Warning: when we talk about Object programming, we


assume patterns programming
● One can use objects the wrong way and don't get
benefit from them at all !
SensioLabs 17
OOP principles

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

is a variable into the class belonging to the future objects


● declared with a default value or not
● declared with a type or not
● declared read-only or not
● is usually declared at the top of the class
● must be initialized through constructor or have a
default value if typed and private or protected

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

is a function written into a class


● Usually declared after properties
● May declare a return type
● May be given arguments.
● Arguments may be typed

SensioLabs 27
Typing things

Properties may be typed, may be read only


● If readonly : must be typed
● Methods return type may be used
● Methods arguments may be typed

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

Types cannot be intersected and unioned at the same


time

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

● "magic" method : called automatically by PHP


● Called when an object is created using the ''new''
keyword
● A constructor cannot return a value
● Any returned value is simply ignored

SensioLabs 38
Constructor

SensioLabs 39
Constructor syntax

Constructor arguments can be “promoted” to properties


by declaring their visibility in the constructor arguments
list.

SensioLabs 40
Constructor syntax

SensioLabs 41
$this

● $this is a special reserved variable


● It represents the object itself into its own class
● It cannot be used:
○ out of object scope
○ out of a class
○ Into the static scope of a class
● It cannot be hand-created or destroyed
● It cannot be used as a function parameter variable

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

Inheritance is a hard link : "is a" , "is a sort of"


You cannot inherit from several classes in PHP

All non private members:


● Are copied and shared into the child class
● May be overridden if not declared final

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

All non private members are ported to child. It can be


overloaded by redeclaring a member with the same name.
A call to parent:: resolves the parent scope.

SensioLabs 52
Parent context

SensioLabs 53
Practice POO : inheritance

● Create an Admin class extending Member


● An admin owns a $level which can be "ADMIN" or "SUPERADMIN"
(defaults to "ADMIN")
● Overwrite the constructor to take this $level parameter into account
● You may use an enum
● If admin has level SUPERADMIN, then auth() will return true regardless
of credentials. Overwrite auth() method to describe such a behavior

SensioLabs 54
Static method /property

The static keyword is used to access the static context.


The static context is used to make any treatment for a class and
not for objects anymore. $this is forbidden in static context.

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

Conventionally, class constants names used to be written in


uppercase.

SensioLabs 62
Class constants

SensioLabs 63
Practice : static and constants

● Go back to our Member and Admin classes :


● Find a way for classes to count the objects created
from themselves
● Use a destructor to only count lived objects
● Publish the result with a count() method

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

● An interface cannot store properties.


● An interface only stores public definitions, not bodies
● Objects cannot be created from interfaces
● At the class level, interfaces are implemented, not
extended
● Every class implementing an interface must define all
of its methods.
● A class can implement several interfaces.

SensioLabs 67
Practice : interfaces

● Your members allow to be authenticated.


● Create an AuthInterface which defines the
auth(string $login, string $password) : bool
method
● Implement it into Member class

SensioLabs 68
Abstract classes

● abstract classes cannot be instantiated


● They are used as a template, and cannot contain private members
● Methods can be declared abstract inside an abstract class
○ Only signatures are declared in this case, as in interfaces
○ child classes must implement the method bodies as for
interfaces
● A private abstract or final abstract method is a nonsense
(and results in a fatal error)

SensioLabs 69
Abstract classes

SensioLabs 70
Abstract class practice

● Our members and admins now inherit from a more


general purpose abstract class : User
● This class contains a $name attribute, its getter and
setter, and a constructor.

SensioLabs 71
Traits

Traits are a system of horizontal inheritance.


A trait is a template :
● It contains code like a class (properties and/or methods)
● You cannot instantiate an object from a trait.
● The trait can be use‘d into a class
● Its code is then magically copied to the class
● You can resolve manually name collisions

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

The Exception class is the base class for all non-fatal


errors that can be handled by your code.
Most exceptions extend the base Exception class, and
you can extend it yourself to create custom exceptions.

SensioLabs 77
The Exception class

SensioLabs 78
Some native Exceptions

SensioLabs 79
Fatal errors

● Fatal errors are Exceptions


from the main Error class.
● Users should not throw
Error, but Exception.
● Generic type is Throwable

SensioLabs 80
Fatal error examples

Error children examples :


● TypeError
● ParseError
● ArithmeticError
● ArgumentCountError
Attention, Warnings and Notices are still Errors and not
treated as Exceptions

SensioLabs 81
Fatal error examples

SensioLabs 82
Practice Exceptions

● Send an exception if authentication fails

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

Using UML (Unified Modeling


Language)

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

● Namespaces are container above classes


● 2 classes/functions/constants can have the same
name if they live in different namespaces
● It allows you to easily program by components
● The namespace separator is \

SensioLabs 104
Namespaces

SensioLabs 105
Namespaces syntax

● The namespace keyword must be the first at the top of


the file
● Brackets based syntax is also possible but not
recommanded
● Both syntaxes can’t be mixed within the same file

SensioLabs 106
Namespaces syntax

SensioLabs 107
Using namespaces

● You can import and alias namespaces using respectively the


keywords use and as.
● Namespaces and the elements they contain are isolated from
one another.
● During namespace resolution of an unknown element, the
current namespace is always considered first, then PHP
bubbles up until the global namespace.
● The global namespace is accessed prefixing accesses by a \

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

The sum of a class’s name and its full namespace is called


the Fully Qualified Class Name (FQCN).

It can be accessed using the PHP function


get_class($object) or the special ::class constant.

SensioLabs 113
Fully Qualified Class Name

SensioLabs 114
Practice namespaces

Refactor our full example to use 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

Autoload our project using Composer and PSR rules

SensioLabs 118

You might also like