SlideShare a Scribd company logo
Architecture logicielle : Object-oriented design
0. Object 101
Object
In computer science, an object is a location in memory having
a value and possibly referenced by an identifier.An object can
be a variable, a data structure, or a function.
Source : http://en.wikipedia.org
Object-oriented programming
Object-Oriented programming is an approach to designing
modular reusable software systems.The object-oriented
approach is fundamentally a modelling approach.
Source : http://en.wikipedia.org
Class
In object-oriented programming, a class is an extensible
program-code-template for creating objects, providing initial
values for state and implementations of behavior.
Source : http://en.wikipedia.org
Class - PHP exemple
class Character {
private $firstName;
private $lastName;
public function __construct($firstName, $lastName) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
Instance
In object-oriented programming (OOP), an instance is a
specific realization of any object.The creation of a realized
instance is called instantiation.
Source : http://en.wikipedia.org
Instance - PHP exemple
$nedStark = new Character('Eddard', 'Stark');
$robertBaratheon = new Character('Robert', 'Baratheon');
Attribute & method
A class contains data field descriptions (or properties, fields,
data members, or attributes).
Source : http://en.wikipedia.org
A method in object-oriented programming (OOP) is a
procedure associated with an object class.
Source : http://en.wikipedia.org
Attribute & method - PHP exemple
class Character {
private $firstName;
private $lastName;
private $nickname;
public function __construct($firstName, $lastName, $nickname) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->nickname = $nickname;
}
public function getFullName(){
return $this->firstName . ' ' . $this->lastName;
}
public function getNickname(){
return $this->nickname;
}
}
$nedStark = new Character('Eddard', 'Stark', 'Ned');
echo $nedStark->getFullName(); // Eddard Stark
echo $nedStark->getNickname(); // Ned
Interface
In object-oriented languages, the term interface is often used
to define an abstract type that contains no data or code, but
defines behaviors as method signatures.A class having code
and data for all the methods corresponding to that interface is
said to implement that interface.
Source : http://en.wikipedia.org
Interface - PHP exemple
interface CharacterInterface {
public function getFullName();
}
class Human implements CharacterInterface {
private $firstName;
private $lastName;
public function __construct($firstName, $lastName) {…}
public function getFullName(){
return $this->firstName . ' ' . $this->lastName;
}
}
class Animal implements CharacterInterface {
private $name;
public function __construct($name) {…}
public function getFullName(){
return $this->name;
}
}
$nedStark = new Human('Eddard', 'Stark', 'Ned');
$nymeria = new Animal('Nymeria');
echo $nedStark->getFullName(); // Eddard Stark
echo $nymeria->getFullName(); // Nymeria
Inheritance
In object-oriented programming (OOP), inheritance is when an
object or class is based on another object or class, using the
same implementation (inheriting from a class) specifying
implementation to maintain the same behavior.
Source : http://en.wikipedia.org
Inheritance - PHP exemple
class Human {
private $firstName;
private $lastName;
public function __construct($firstName, $lastName) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFullName(){
return $this->firstName . ' ' . $this->lastName;
}
}
class King extends Human {
private $reignStart;
private $reignEnd;
public function setReign($reignStart, $reignEnd){
$this->reignStart = $reignStart;
$this->reignEnd = $reignEnd;
}
public function getReign(){
return $this->reignStart . " - " . $this->reignEnd;
}
}
$robertBaratheon = new King('Robert', 'Baratheon');
$robertBaratheon->setReign(283, 298);
echo $robertBaratheon->getFullName() . ' ( '.$robertBaratheon->getReign().' )';
// Robert Baratheon ( 283 - 298 )
2. Are You Stupid?
STUPID code, seriously?
Singleton
Tight Coupling
Untestability
Premature Optimization
Indescriptive Naming
Duplication
2.1 Singleton
Singleton syndrome
class Database
{
const DB_DSN = 'mysql:host=localhost;port=3306;dbname=westeros';
const DB_USER = 'root';
const DB_PWD = 'root';
private $dbh;
static private $instance;
private function connect()
{
if ($this->dbh instanceOf PDO) {return;}
$this->dbh = new PDO(self::DB_DSN, self::DB_USER, self::DB_PWD);
}
public function query($sql)
{
$this->connect();
return $this->dbh->query($sql);
}
public static function getInstance()
{
if (null !== self::$instance) {
return self::$instance;
}
self::$instance = new self();
return self::$instance;
}
}
Configuration difficile
singletons ~ variables globales
Couplages forts
Difficile à tester
2.2 Tight Coupling
Coupling ?
In software engineering, coupling is the manner and degree of
interdependence between software modules; a measure of
how closely connected two routines or modules are; the
strength of the relationships between modules.
Source : http://en.wikipedia.org
Et en claire ?
If making a change in one module in your
application requires you to change another
module, then coupling exists.
Exemple de couplage fort
class Location {
private $name;
private $type;
}
class Character {
private $firstName;
private $lastName;
private $location;
public function __construct($firstName, $lastName, $locationName, $locationType) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->location = new Location($locationName, $locationType);
}
public function getFullName(){
return $this->firstName . ' ' . $this->lastName;
}
}
$nedStark = new Character('Eddard', 'Stark', 'Winterfell', 'Castle');
Exemple de couplage faible
class Location {
private $name;
private $type;
}
class Character {
private $firstName;
private $lastName;
private $location;
public function __construct($firstName, $lastName, $location) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->location = $location;
}
public function getFullName(){
return $this->firstName . ' ' . $this->lastName;
}
}
$winterfell = new Location($locationName, $locationType);
$nedStark = new Character('Eddard', 'Stark', $winterfell);
2.3 Untestability
Testing ?
In my opinion, testing should not be hard! No, really.Whenever
you don't write unit tests because you don't have time, the
real issue is that your code is bad, but that is another story.
Source : http://williamdurand.fr
Untested and Untestable
2.4 Premature Optimization
« Premature optimization
is the root of all evil. »
Donald Knuth
« If it doesn't work, it
doesn't matter how fast it
doesn't work. »
Mich Ravera
2.5 Indescriptive Naming
Give all entities mentioned in the code (DB tables, DB tables’
fields, variables, classes, functions, etc.) meaningful, descriptive
names that make the code easily understood.The names
should be so self-explanatory that it eliminates the need for
comments in most cases.
Source : Michael Zuskin
Self-explanatory
Exemple : bad names
« If you can't find a decent
name for a class or a
method, something is
probably wrong »
William Durand
class Char {
private $fn;
private $ln;
public function __construct($fn, $ln) {
$this->fn = $fn;
$this->ln = $ln;
}
public function getFnLn(){
return $this->fn . ' ' . $this->ln;
}
}
Exemple : abbreviations
2.6 Duplication
« Write Everything Twice »
WET ?
« We Enjoy Typing »
Copy-and-paste programming is the production of highly
repetitive computer programming code, as by copy and paste
operations. It is primarily a pejorative term; those who use the
term are often implying a lack of programming competence.
Source : http://en.wikipedia.org
Copy And Paste Programming
« Every piece of knowledge must have
a single, unambiguous, authoritative
representation within a system. »
Don’t Repeat Yourself
Andy Hunt & Dave Thomas
The KISS principle states that most systems work best if they
are kept simple rather than made complicated; therefore
simplicity should be a key goal in design and unnecessary
complexity should be avoided.
Keep it simple, stupid
Source : http://en.wikipedia.org
3. Nope, Im solid !
SOLID code ?
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
3.1 Single Responsibility Principle
Single Responsibility
A class should have one, and
only one, reason to change.
Robert C. Martin
The problem
class DataImporter
{
public function import($file)
{
$records = $this->loadFile($file);
$this->importData($records);
}
private function loadFile($file)
{
$records = array();
// transform CSV in $records
return $records;
}
private function importData(array $records)
{
// insert records in DB
}
}
The solution
class DataImporter
{
private $loader;
private $importer;
public function __construct($loader, $gateway)
{
$this->loader = $loader;
$this->gateway = $gateway;
}
public function import($file)
{
$records = $this->loader->load($file);
foreach ($records as $record) {
$this->gateway->insert($record);
}
}
}
Kill the god class !
A "God Class" is an object that
controls way too many other objects
in the system and has grown beyond
all logic to become The Class That
Does Everything.
3.2 Open/Closed Principle
Open/Closed
Objects or entities should be
open for extension, but closed
for modification.
Robert C. Martin
The problem
class Circle {
public $radius;
// Constructor function
}
class Square {
public $length;
// Constructor function
}
class AreaCalculator {
protected $shapes;
// Constructor function
public function sum() {
foreach($this->shapes as $shape) {
if(is_a($shape, 'Square')) {
$area[] = pow($shape->length, 2);
} else if(is_a($shape, 'Circle')) {
$area[] = pi() * pow($shape->radius, 2);
}
}
return array_sum($area);
}
}
$shapes = array(
new Circle(2),
new Square(5),
new Square(6)
);
$areas = new AreaCalculator($shapes);
echo $areas->sum();
Source : https://scotch.io
The solution (1)
class Circle {
public $radius;
// Constructor function
public function area() {
return pi() * pow($this->radius, 2);
}
}
class Square {
public $length;
// Constructor function
public function area() {
return pow($this->length, 2);
}
}
class AreaCalculator {
protected $shapes;
// Constructor function
public function sum() {
foreach($this->shapes as $shape) {
$area[] = $shape->area();
}
return array_sum($area);
}
}
$shapes = array(
new Circle(2),
new Square(5),
new Square(6)
);
$areas = new AreaCalculator($shapes);
echo $areas->sum();
Source : https://scotch.io
The solution (2)
class AreaCalculator {
protected $shapes;
// Constructor function
public function sum() {
foreach($this->shapes as $shape) {
$area[] = $shape->area();
}
return array_sum($area);
}
}
$shapes = array(
new Circle(2),
new Square(5),
new Square(6)
);
$areas = new AreaCalculator($shapes);
echo $areas->sum();
interface ShapeInterface {
public function area();
}
class Circle implements ShapeInterface {
public $radius;
// Constructor function
public function area() {
return pi() * pow($this->radius, 2);
}
}
class Square implements ShapeInterface {
public $length;
// Constructor function
public function area() {
return pow($this->length, 2);
}
}
Source : https://scotch.io
3.3 Liskov Substitution Principle
Liskov Substitution
Derived classes must be
substitutable for their
base classes.Robert C. Martin
Exemple
abstract class AbstractLoader implements FileLoader
{
public function load($file)
{
if (!file_exists($file)) {
throw new InvalidArgumentException(sprintf('%s does not exist.', $file));
}
return [];
}
}
class CsvFileLoader extends AbstractLoader
{
public function load($file)
{
$records = parent::load($file);
// Get records from file
return $records;
}
}
Source : http://afsy.fr
3.4 Interface Segregation Principle
Interface Segregation
A client should never be forced to
implement an interface that it doesn’t
use or clients shouldn’t be forced to
depend on methods they do not use.
Robert C. Martin
Exemple
interface UrlGeneratorInterface
{
public function generate($name, $parameters = array());
}
interface UrlMatcherInterface
{
public function match($pathinfo);
}
interface RouterInterface extends UrlMatcherInterface, UrlGeneratorInterface
{
public function getRouteCollection();
}
Source : http://afsy.fr
3.5 Dependency Inversion Principle
Dependency Inversion
Entities must depend on abstractions not
on concretions. It states that the high
level module must not depend on the
low level module, but they should
depend on abstractions.
Robert C. Martin
The problem
class DataImporter
{
private $loader;
private $gateway;
public function __construct(CsvFileLoader $loader, DataGateway $gateway)
{
$this->loader = $loader;
$this->gateway = $gateway;
}
}
Source : http://afsy.fr
Classes
The solution
Source : http://afsy.fr
class DataImporter
{
private $loader;
private $gateway;
public function __construct(FileLoader $loader, Gateway $gateway)
{
$this->loader = $loader;
$this->gateway = $gateway;
}
}
Interfaces
To be continued …

More Related Content

PPTX
Ch8(oop)
PDF
OOP in PHP
PPT
Advanced php
PDF
Object Oriented Programming with PHP 5 - More OOP
PPT
Class and Objects in PHP
PDF
Object Oriented Programming in PHP
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Ch8(oop)
OOP in PHP
Advanced php
Object Oriented Programming with PHP 5 - More OOP
Class and Objects in PHP
Object Oriented Programming in PHP
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA

What's hot (20)

PPT
Class 7 - PHP Object Oriented Programming
ZIP
Object Oriented PHP5
PPTX
Oop in-php
KEY
Xtext Eclipse Con
PPT
Php object orientation and classes
PDF
PHP OOP
PPT
Synapseindia object oriented programming in php
PDF
A Gentle Introduction To Object Oriented Php
PPTX
Object oriented programming with python
PPTX
Python OOPs
PPT
Oops in PHP
PPTX
Object oriented programming in python
PPTX
Object oreinted php | OOPs
PPTX
Basics of Object Oriented Programming in Python
DOCX
Oops concept in php
PPT
Introduction to OOP with PHP
PDF
09 Object Oriented Programming in PHP #burningkeyboards
PPTX
Python oop third class
Class 7 - PHP Object Oriented Programming
Object Oriented PHP5
Oop in-php
Xtext Eclipse Con
Php object orientation and classes
PHP OOP
Synapseindia object oriented programming in php
A Gentle Introduction To Object Oriented Php
Object oriented programming with python
Python OOPs
Oops in PHP
Object oriented programming in python
Object oreinted php | OOPs
Basics of Object Oriented Programming in Python
Oops concept in php
Introduction to OOP with PHP
09 Object Oriented Programming in PHP #burningkeyboards
Python oop third class
Ad

Viewers also liked (20)

PDF
Javascript #9 : barbarian quest
PDF
Architecture logicielle #5 : hipsto framework
PDF
WebApp #2 : responsive design
PDF
Javascript #4.2 : fonctions for pgm
PDF
Javascript #11: Space invader
PDF
PHP #3 : tableaux & formulaires
PDF
Javascript #10 : canvas
PDF
Javascript #3 : boucles & conditions
PDF
Javascript #5.1 : tp1 zombies!
PDF
Architecture logicielle #2 : TP timezone
PDF
#1 entreprendre au xxiè siècle
PDF
PHP #4 : sessions & cookies
PDF
WebApp #4 : Consuming REST APIs
PDF
PHP & MYSQL #5 : fonctions
PDF
PHP #7 : guess who?
PDF
Html & Css #5 : positionement
PDF
Javascript #7 : manipuler le dom
PDF
Javascript #6 : objets et tableaux
PDF
#4 css 101
PDF
Les modèles économiques du web
Javascript #9 : barbarian quest
Architecture logicielle #5 : hipsto framework
WebApp #2 : responsive design
Javascript #4.2 : fonctions for pgm
Javascript #11: Space invader
PHP #3 : tableaux & formulaires
Javascript #10 : canvas
Javascript #3 : boucles & conditions
Javascript #5.1 : tp1 zombies!
Architecture logicielle #2 : TP timezone
#1 entreprendre au xxiè siècle
PHP #4 : sessions & cookies
WebApp #4 : Consuming REST APIs
PHP & MYSQL #5 : fonctions
PHP #7 : guess who?
Html & Css #5 : positionement
Javascript #7 : manipuler le dom
Javascript #6 : objets et tableaux
#4 css 101
Les modèles économiques du web
Ad

Similar to Architecture logicielle #3 : object oriented design (20)

PPTX
Oopsinphp
PPTX
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT III (8).pptx
PPTX
UNIT III (8).pptx
PDF
OOP in PHP
PPTX
Php oop (1)
PPTX
Lecture-10_PHP-OOP.pptx
PDF
Demystifying Object-Oriented Programming #phpbnl18
PDF
Take the Plunge with OOP from #pnwphp
PDF
Demystifying Object-Oriented Programming - PHP[tek] 2017
PPT
PPTX
Object oriented programming
PDF
Demystifying Object-Oriented Programming - PHP UK Conference 2017
PPTX
[OOP - Lec 04,05] Basic Building Blocks of OOP
PPTX
Intro to oop.pptx
PPTX
PDF
OOPs Concept
PPT
Object Oriented Design
PPT
Object Oriented Design
PPTX
Advance oops concepts
Oopsinphp
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT III (8).pptx
UNIT III (8).pptx
OOP in PHP
Php oop (1)
Lecture-10_PHP-OOP.pptx
Demystifying Object-Oriented Programming #phpbnl18
Take the Plunge with OOP from #pnwphp
Demystifying Object-Oriented Programming - PHP[tek] 2017
Object oriented programming
Demystifying Object-Oriented Programming - PHP UK Conference 2017
[OOP - Lec 04,05] Basic Building Blocks of OOP
Intro to oop.pptx
OOPs Concept
Object Oriented Design
Object Oriented Design
Advance oops concepts

More from Jean Michel (19)

PDF
Startup #7 : how to get customers
PDF
Javascript #2.2 : jQuery
PDF
HTML & CSS #10 : Bootstrap
PDF
Architecture logicielle #4 : mvc
PDF
Wordpress #3 : content strategie
PDF
Architecture logicielle #1 : introduction
PDF
Wordpress #2 : customisation
PDF
Wordpress #1 : introduction
PDF
PHP #6 : mysql
PDF
PHP #2 : variables, conditions & boucles
PDF
PHP #1 : introduction
PDF
Dev Web 101 #2 : development for dummies
PDF
Startup #5 : pitch
PDF
Javascript #8 : événements
PDF
Projet timezone
PDF
WebApp #3 : API
PDF
Gestion de projet #4 : spécification
PDF
Projet timezone
PDF
WebApp #1 : introduction
Startup #7 : how to get customers
Javascript #2.2 : jQuery
HTML & CSS #10 : Bootstrap
Architecture logicielle #4 : mvc
Wordpress #3 : content strategie
Architecture logicielle #1 : introduction
Wordpress #2 : customisation
Wordpress #1 : introduction
PHP #6 : mysql
PHP #2 : variables, conditions & boucles
PHP #1 : introduction
Dev Web 101 #2 : development for dummies
Startup #5 : pitch
Javascript #8 : événements
Projet timezone
WebApp #3 : API
Gestion de projet #4 : spécification
Projet timezone
WebApp #1 : introduction

Recently uploaded (20)

PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Transform Your Business with a Software ERP System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
top salesforce developer skills in 2025.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Digital Strategies for Manufacturing Companies
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Nekopoi APK 2025 free lastest update
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPT
Introduction Database Management System for Course Database
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
L1 - Introduction to python Backend.pptx
Transform Your Business with a Software ERP System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
top salesforce developer skills in 2025.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
CHAPTER 2 - PM Management and IT Context
Digital Strategies for Manufacturing Companies
Wondershare Filmora 15 Crack With Activation Key [2025
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Odoo POS Development Services by CandidRoot Solutions
Nekopoi APK 2025 free lastest update
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Design an Analysis of Algorithms I-SECS-1021-03
Introduction Database Management System for Course Database
How Creative Agencies Leverage Project Management Software.pdf
Softaken Excel to vCard Converter Software.pdf

Architecture logicielle #3 : object oriented design

  • 1. Architecture logicielle : Object-oriented design
  • 3. Object In computer science, an object is a location in memory having a value and possibly referenced by an identifier.An object can be a variable, a data structure, or a function. Source : http://en.wikipedia.org
  • 4. Object-oriented programming Object-Oriented programming is an approach to designing modular reusable software systems.The object-oriented approach is fundamentally a modelling approach. Source : http://en.wikipedia.org
  • 5. Class In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state and implementations of behavior. Source : http://en.wikipedia.org
  • 6. Class - PHP exemple class Character { private $firstName; private $lastName; public function __construct($firstName, $lastName) { $this->firstName = $firstName; $this->lastName = $lastName; } }
  • 7. Instance In object-oriented programming (OOP), an instance is a specific realization of any object.The creation of a realized instance is called instantiation. Source : http://en.wikipedia.org
  • 8. Instance - PHP exemple $nedStark = new Character('Eddard', 'Stark'); $robertBaratheon = new Character('Robert', 'Baratheon');
  • 9. Attribute & method A class contains data field descriptions (or properties, fields, data members, or attributes). Source : http://en.wikipedia.org A method in object-oriented programming (OOP) is a procedure associated with an object class. Source : http://en.wikipedia.org
  • 10. Attribute & method - PHP exemple class Character { private $firstName; private $lastName; private $nickname; public function __construct($firstName, $lastName, $nickname) { $this->firstName = $firstName; $this->lastName = $lastName; $this->nickname = $nickname; } public function getFullName(){ return $this->firstName . ' ' . $this->lastName; } public function getNickname(){ return $this->nickname; } } $nedStark = new Character('Eddard', 'Stark', 'Ned'); echo $nedStark->getFullName(); // Eddard Stark echo $nedStark->getNickname(); // Ned
  • 11. Interface In object-oriented languages, the term interface is often used to define an abstract type that contains no data or code, but defines behaviors as method signatures.A class having code and data for all the methods corresponding to that interface is said to implement that interface. Source : http://en.wikipedia.org
  • 12. Interface - PHP exemple interface CharacterInterface { public function getFullName(); } class Human implements CharacterInterface { private $firstName; private $lastName; public function __construct($firstName, $lastName) {…} public function getFullName(){ return $this->firstName . ' ' . $this->lastName; } } class Animal implements CharacterInterface { private $name; public function __construct($name) {…} public function getFullName(){ return $this->name; } } $nedStark = new Human('Eddard', 'Stark', 'Ned'); $nymeria = new Animal('Nymeria'); echo $nedStark->getFullName(); // Eddard Stark echo $nymeria->getFullName(); // Nymeria
  • 13. Inheritance In object-oriented programming (OOP), inheritance is when an object or class is based on another object or class, using the same implementation (inheriting from a class) specifying implementation to maintain the same behavior. Source : http://en.wikipedia.org
  • 14. Inheritance - PHP exemple class Human { private $firstName; private $lastName; public function __construct($firstName, $lastName) { $this->firstName = $firstName; $this->lastName = $lastName; } public function getFullName(){ return $this->firstName . ' ' . $this->lastName; } } class King extends Human { private $reignStart; private $reignEnd; public function setReign($reignStart, $reignEnd){ $this->reignStart = $reignStart; $this->reignEnd = $reignEnd; } public function getReign(){ return $this->reignStart . " - " . $this->reignEnd; } } $robertBaratheon = new King('Robert', 'Baratheon'); $robertBaratheon->setReign(283, 298); echo $robertBaratheon->getFullName() . ' ( '.$robertBaratheon->getReign().' )'; // Robert Baratheon ( 283 - 298 )
  • 15. 2. Are You Stupid?
  • 16. STUPID code, seriously? Singleton Tight Coupling Untestability Premature Optimization Indescriptive Naming Duplication
  • 19. class Database { const DB_DSN = 'mysql:host=localhost;port=3306;dbname=westeros'; const DB_USER = 'root'; const DB_PWD = 'root'; private $dbh; static private $instance; private function connect() { if ($this->dbh instanceOf PDO) {return;} $this->dbh = new PDO(self::DB_DSN, self::DB_USER, self::DB_PWD); } public function query($sql) { $this->connect(); return $this->dbh->query($sql); } public static function getInstance() { if (null !== self::$instance) { return self::$instance; } self::$instance = new self(); return self::$instance; } } Configuration difficile singletons ~ variables globales Couplages forts Difficile à tester
  • 21. Coupling ? In software engineering, coupling is the manner and degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules. Source : http://en.wikipedia.org
  • 22. Et en claire ? If making a change in one module in your application requires you to change another module, then coupling exists.
  • 23. Exemple de couplage fort class Location { private $name; private $type; } class Character { private $firstName; private $lastName; private $location; public function __construct($firstName, $lastName, $locationName, $locationType) { $this->firstName = $firstName; $this->lastName = $lastName; $this->location = new Location($locationName, $locationType); } public function getFullName(){ return $this->firstName . ' ' . $this->lastName; } } $nedStark = new Character('Eddard', 'Stark', 'Winterfell', 'Castle');
  • 24. Exemple de couplage faible class Location { private $name; private $type; } class Character { private $firstName; private $lastName; private $location; public function __construct($firstName, $lastName, $location) { $this->firstName = $firstName; $this->lastName = $lastName; $this->location = $location; } public function getFullName(){ return $this->firstName . ' ' . $this->lastName; } } $winterfell = new Location($locationName, $locationType); $nedStark = new Character('Eddard', 'Stark', $winterfell);
  • 27. In my opinion, testing should not be hard! No, really.Whenever you don't write unit tests because you don't have time, the real issue is that your code is bad, but that is another story. Source : http://williamdurand.fr Untested and Untestable
  • 29. « Premature optimization is the root of all evil. » Donald Knuth
  • 30. « If it doesn't work, it doesn't matter how fast it doesn't work. » Mich Ravera
  • 32. Give all entities mentioned in the code (DB tables, DB tables’ fields, variables, classes, functions, etc.) meaningful, descriptive names that make the code easily understood.The names should be so self-explanatory that it eliminates the need for comments in most cases. Source : Michael Zuskin Self-explanatory
  • 33. Exemple : bad names
  • 34. « If you can't find a decent name for a class or a method, something is probably wrong » William Durand
  • 35. class Char { private $fn; private $ln; public function __construct($fn, $ln) { $this->fn = $fn; $this->ln = $ln; } public function getFnLn(){ return $this->fn . ' ' . $this->ln; } } Exemple : abbreviations
  • 37. « Write Everything Twice » WET ? « We Enjoy Typing »
  • 38. Copy-and-paste programming is the production of highly repetitive computer programming code, as by copy and paste operations. It is primarily a pejorative term; those who use the term are often implying a lack of programming competence. Source : http://en.wikipedia.org Copy And Paste Programming
  • 39. « Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. » Don’t Repeat Yourself Andy Hunt & Dave Thomas
  • 40. The KISS principle states that most systems work best if they are kept simple rather than made complicated; therefore simplicity should be a key goal in design and unnecessary complexity should be avoided. Keep it simple, stupid Source : http://en.wikipedia.org
  • 41. 3. Nope, Im solid !
  • 42. SOLID code ? Single Responsibility Principle Open/Closed Principle Liskov Substitution Principle Interface Segregation Principle Dependency Inversion Principle
  • 44. Single Responsibility A class should have one, and only one, reason to change. Robert C. Martin
  • 45. The problem class DataImporter { public function import($file) { $records = $this->loadFile($file); $this->importData($records); } private function loadFile($file) { $records = array(); // transform CSV in $records return $records; } private function importData(array $records) { // insert records in DB } }
  • 46. The solution class DataImporter { private $loader; private $importer; public function __construct($loader, $gateway) { $this->loader = $loader; $this->gateway = $gateway; } public function import($file) { $records = $this->loader->load($file); foreach ($records as $record) { $this->gateway->insert($record); } } }
  • 47. Kill the god class ! A "God Class" is an object that controls way too many other objects in the system and has grown beyond all logic to become The Class That Does Everything.
  • 49. Open/Closed Objects or entities should be open for extension, but closed for modification. Robert C. Martin
  • 50. The problem class Circle { public $radius; // Constructor function } class Square { public $length; // Constructor function } class AreaCalculator { protected $shapes; // Constructor function public function sum() { foreach($this->shapes as $shape) { if(is_a($shape, 'Square')) { $area[] = pow($shape->length, 2); } else if(is_a($shape, 'Circle')) { $area[] = pi() * pow($shape->radius, 2); } } return array_sum($area); } } $shapes = array( new Circle(2), new Square(5), new Square(6) ); $areas = new AreaCalculator($shapes); echo $areas->sum(); Source : https://scotch.io
  • 51. The solution (1) class Circle { public $radius; // Constructor function public function area() { return pi() * pow($this->radius, 2); } } class Square { public $length; // Constructor function public function area() { return pow($this->length, 2); } } class AreaCalculator { protected $shapes; // Constructor function public function sum() { foreach($this->shapes as $shape) { $area[] = $shape->area(); } return array_sum($area); } } $shapes = array( new Circle(2), new Square(5), new Square(6) ); $areas = new AreaCalculator($shapes); echo $areas->sum(); Source : https://scotch.io
  • 52. The solution (2) class AreaCalculator { protected $shapes; // Constructor function public function sum() { foreach($this->shapes as $shape) { $area[] = $shape->area(); } return array_sum($area); } } $shapes = array( new Circle(2), new Square(5), new Square(6) ); $areas = new AreaCalculator($shapes); echo $areas->sum(); interface ShapeInterface { public function area(); } class Circle implements ShapeInterface { public $radius; // Constructor function public function area() { return pi() * pow($this->radius, 2); } } class Square implements ShapeInterface { public $length; // Constructor function public function area() { return pow($this->length, 2); } } Source : https://scotch.io
  • 54. Liskov Substitution Derived classes must be substitutable for their base classes.Robert C. Martin
  • 55. Exemple abstract class AbstractLoader implements FileLoader { public function load($file) { if (!file_exists($file)) { throw new InvalidArgumentException(sprintf('%s does not exist.', $file)); } return []; } } class CsvFileLoader extends AbstractLoader { public function load($file) { $records = parent::load($file); // Get records from file return $records; } } Source : http://afsy.fr
  • 57. Interface Segregation A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use. Robert C. Martin
  • 58. Exemple interface UrlGeneratorInterface { public function generate($name, $parameters = array()); } interface UrlMatcherInterface { public function match($pathinfo); } interface RouterInterface extends UrlMatcherInterface, UrlGeneratorInterface { public function getRouteCollection(); } Source : http://afsy.fr
  • 60. Dependency Inversion Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions. Robert C. Martin
  • 61. The problem class DataImporter { private $loader; private $gateway; public function __construct(CsvFileLoader $loader, DataGateway $gateway) { $this->loader = $loader; $this->gateway = $gateway; } } Source : http://afsy.fr Classes
  • 62. The solution Source : http://afsy.fr class DataImporter { private $loader; private $gateway; public function __construct(FileLoader $loader, Gateway $gateway) { $this->loader = $loader; $this->gateway = $gateway; } } Interfaces