SlideShare une entreprise Scribd logo
1  sur  53
Télécharger pour lire hors ligne
PHP Leeds, Wales, United Kingdom
Strong typing in PHP
adoption, evolution and organisation
AGENDA
• PHPType hints syste
m

• Adoptio
n

• Evolutio
n

• Organisation
SPEAKER
• Damien Segu
y

• CTO @exaka
t

• Static analysis exper
t

• Retirement home for elePHPants
Everyone uses typehinting
3 %
97 %
With Typehints Without typehint
No
type
hints
Adoption Hard
part
A
d
or
at
or
s
Everyone uses typehinting
Adoption
Typehints as debug tactics
• Set up a typehint


• Wait for the 'Fatal error'


• Fix the calling code, now that you know where it is


• Remove it in production


• Leave it in development
<?php 


foo("a");


foo(1);


foo(new x);


foo(array());


function foo(string $s) {


    echo $s;


}


class x {


    function __toString() 


{ return "a"; }


}


?>
Your code is already typed
• Typehints are already used in the code


• PHP, and strict_types


• is_string(), is_array(), instanceof…


• Coding conventions
Coding conventions
• The type is in the name of the argument


• $string, $array


• $user = new User();
<?php   
 

function shorten($string) {   
 

   return substr($string, 0, 5);
 

}

  
 

function getPattern(array $ints) {   
}

function (StringClass $string)  {   
}

?>
Moving type checks to the signature
• is_a(), is_subclass_of(), instanceof, === null


• is_string(), is_array()


• (int), (string)…
<?php  


function bar($user) {  


  if ($user === null) {


     throw new TypeError(); 


  }


  


  if (!$user instanceof User)) { 


     throw new TypeError(); 


  } 


   return $user->validate(); 


} 


?>
Moving type checks to the signature
• is_a(), is_subclass_of(), instanceof, === null


• is_string(), is_array()


• (int), (string)…
<?php  


function bar(Usager $user) {  


   return $user->validate(); 


} 


?>
Moving type checks to the signature
• is_a(), is_subclass_of(), instanceof, === null


• is_string(), is_array()


• (int), (string)…
<?php
 

function bar($price) {   
 

   return floor((float) $price) * 1.21;  
 

}  
 

?>
Follow the lead
<?php
 

function bar($argument) { 
 

    return substr($argument, 0, 10);
 

}  
 

?>
Follow the lead
<?php
 

function bar(string $argument) { 
 

    return substr($argument, 0, 10);
 

}  
 

?>
Follow the lead
<?php
 

function bar($argument) : string { 
 

    return substr($argument, 0, 10);
 

}  
 

?>
Follow the lead
<?php
 

function bar(string $argument) : string { 
 

    return substr($argument, 0, 10) ?: '';
 

}  
 

?>
Substr() returns string OR false
N
O
T
I
N
P
H
P
8
.
0
R
C
1
Backward with the return types
<?php
 

function bar($argument) { 
 

    return foo($argument);
 

}  
 

function foo($x) { 
 

    return barbar($x);
 

}  
 

function barbar($y) : string { 
 

//...
}  
 

?>
Forward with caution
<?php
 

function bar3($argument) { 
 

    return foo(null);
 

}  
 

?>
<?php
 

function bar($argument) { 
 

    return foo($argument);
 

}  
 

function foo($x) { 
 

    return barbar($x);
 

}  
 

function barbar(string $y) { 
 

//...
}  
 

?>
<?php
 

function bar2($argument) { 
 

    return foo(22);
 

}  
 

?>
Wait for PHP 8.0
<?php 
 

function foo($x) {  
 

   if (rand(1, 3)) {
 

     return 1;
 

   }  else {
 

     return barbar($x); 
 

  }
 

}   
 

function barbar($y) : string {  
 

//...
 

}   
 

?>
Adoption
• Use it for debugging purposes


• Follow the types that are already there


• PHP


• Your framework


• Propagate your own types


• Return types are easy, argument types need caution
Evolution
Evolution
• Typehints now have impact on your code


• Wait for PHP 8.0 union types


• Single type is a constraint and a tool
Impact of defaults
<?php 
 

function foo($x = -1) {  
 

   if ($x === -1) {
 

     return '';
 

   }  else {
 

     return substr($x, 0, 1);
 

  }
 

}   
 

?>
Impact of defaults
<?php
 

class foo {
 

  const DEFAULT = -1;
 

 

  private $bar = self::DEFAULT;
 

  public function foo() {   
 

   if ($this->bar === DEFAULT) { 
 

     return ''; 
 

   }  else { 
 

     return substr($this->bar, 0, 1); 
 

  } 
 

}    
 

?>
Ambiguous cases
<?php 
 

  function foo($b) {
 

    return array_fill(0, 10, $b);
 

  }
 

  function bar($a) {
 

    return shell_exec($a);
 

  }
 

?>
Ambiguous cases
<?php    
 

declare(strict_types = 1);
 

function foo(array $a) { }
 

foo(['a', 'b', 'c', 'd' ]);
 

foo(['a', 'b', 'c', null, 2]);
 

?>
• array()


• No generic in PHP


• Use attributes and


annotations
Dubious cases
<?php    
 

declare(strict_types = 1);
 

class x {
 

function __set($name, $a) {
 

//..
.

}
 

}
 

$x = (new x);
 

$x->c = 3;
 

?>
Fossilisation stage
C2 extends C1
C1
M1()
M1()
• Method signatures


• Arguments count


• Compulsory versus optional


• Type


• Default values


• Visibility
Fossilisation stage
• Modify M1() in C3


• Modify M1() in C1


• Modify M1() in C2 and C4


• Modify M1() in C5


• Modify M1() in C6


• … C2
C1
C3 C4
C5
C6
Evolution
n
o

type
scalar types class


types
non-null
 

interfaces
Evolution
0 %
17,5 %
35 %
52,5 %
70 %
object iterable callable int bool void string array scalar Classes
Evolution
• Scalar types cannot evolve


• Classes can evolve


• Class types don't need to be complex


• A price is not an int/
fl
oat


• A path may be a string while a string is not a path
Evolution
n
o

type
scalar types
class


types
non-null
 

interfaces
No types
Evolution
f1 ($a) : s
f2 ($a) : s
f3 ($a) : s
f5 ($a) : s
f4 ($a) : s
($a) : s
f
Also no types
Evolution
f1 ($a) : s
f2 ($a) : s
f3 ($a) : s
f5 ($a) : s
f4 ($a) : s
($a) : s
f
Evolution
f1 ($a) : s
f2 ($a) : s
f3 ($a) : s
f5 ($a) : s
f4 ($a) : s
($a) : s
f
• Type hints reduces the number of possible paths in
the code


• Scalar are versatile


• They have a lot of connectivity


• Upgrading scalar types to class types reduce
complexity even more
Scalar types to classes
Evolution
f1 ($a) : s
f2 ($a) : s
f3 ($a) : s
f5 ($a) : s
f4 ($a) : s
($a) : s
f
Organisation
Organisation
• Typehinting has impact on the signature of a method


• This impact spreads all over the application


• It introduces a hierarchy of the classes
Classes order
Organisation
• A method returns one type


• A method has dependencies on
its arguments's type


• That object must be created
fi
rst


• A method has dependencies on
its constructor too
C1
M1()
__construct()
Classes order
Organisation
• A method returns one type


• A method has dependencies on
its arguments's type


• That object must be created
fi
rst


• A method has dependencies on
its constructor too
C1
M1()
Classes order
Organisation
C5
C1
C3
C2
• Mysql (C1)


• Host/Login/Pwd (C2)


• Prepare (M1)


• Query (C3)
C1
M1()
Classes order
Organisation
C5
C1
C3
C2
• Mysql (C1)


• Host/Login/Pwd (C2)


• Prepare (M1)


• Query (C3)
C5
C1
C3 C2
C5
C1
C3
C2
C5
C1 C3
C2
Classes order
Organisation
• Topological sorting of the classes


• One class has priority over another class when it is used as typehint


• There is no garantee for a single top class :


• Probably several top classes


• With scalar as argument, because they are so easy to tweak
C5
C1
C3
C2
Classes order
Organisation
Classes order
Organisation
Subsidiary questions
Organisation
• Why are there multiple methods with the same typehints?


• Potential double work


• How testable are the classes?


• How many objects do you need to create an instance?


• Can a method reach a speci
fi
c type of class?


• The needed types may not be available
Adding typehints to your code base
• Adoption


• Follow the current code


• Evolution


• Refactor the code, use classes as typehints


• Organisation


• Use typehints to reduce complexity and plan evolutions
Subsidiary questions
Static analysis helps you type
• Exakat


• Typehint suggestion report, type inconsistencies and typehint report


• Phpdoctor


• Reports missing types


• Psalm


• Infers typehints on the
fl
y
Subsidiary questions
Static analysis helps you type
• Exakat


• Typehint suggestion report, type inconsistencies and typehint report


• Phpdoctor


• Reports missing types


• Psalm


• Infers typehints on the
fl
y
https://www.exakat.io/ | @exakat
O, diolch yn
fawr iawn
Classes order
Organisation
M1
M2
C1
M1()
__construct() M2()
• M1 needs a property


• M2 provides that property


• M2 > M1()


• True in PHP 7.4+


• x::$a must not be accessed before
initialization


• True in PHP 7.0


• Call to a member function bar() on
null

Contenu connexe

Tendances

Perl Intro 3 Datalog Parsing
Perl Intro 3 Datalog ParsingPerl Intro 3 Datalog Parsing
Perl Intro 3 Datalog Parsing
Shaun Griffith
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
jeffz
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
Juan Maiz
 

Tendances (20)

Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Scala syntax analysis
Scala syntax analysisScala syntax analysis
Scala syntax analysis
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Perl Intro 3 Datalog Parsing
Perl Intro 3 Datalog ParsingPerl Intro 3 Datalog Parsing
Perl Intro 3 Datalog Parsing
 
Introduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogic
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Intermediate JavaScript
Intermediate JavaScriptIntermediate JavaScript
Intermediate JavaScript
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Java, what's next?
Java, what's next?Java, what's next?
Java, what's next?
 
introduction to c #
introduction to c #introduction to c #
introduction to c #
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
 
Variables and Data Types
Variables and Data TypesVariables and Data Types
Variables and Data Types
 
Type Casting Operator
Type Casting OperatorType Casting Operator
Type Casting Operator
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 

Similaire à Strong typing @ php leeds

José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...
José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...
José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...
RootedCON
 

Similaire à Strong typing @ php leeds (20)

Uni texus austin
Uni texus austinUni texus austin
Uni texus austin
 
A Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and UnderstandingA Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and Understanding
 
TAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith AdamsTAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith Adams
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdf
 
50 shades of PHP
50 shades of PHP50 shades of PHP
50 shades of PHP
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Scala in practice - 3 years later
Scala in practice - 3 years laterScala in practice - 3 years later
Scala in practice - 3 years later
 
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Python ppt
Python pptPython ppt
Python ppt
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!
 
José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...
José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...
José Miguel Esparza - Obfuscation and (non-)detection of malicious PDF files ...
 
Talking to your IDE
Talking to your IDETalking to your IDE
Talking to your IDE
 
Professional Help for PowerShell Modules
Professional Help for PowerShell ModulesProfessional Help for PowerShell Modules
Professional Help for PowerShell Modules
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Groovy DSLs - S2GForum London 2011 - Guillaume Laforge
Groovy DSLs - S2GForum London 2011 - Guillaume LaforgeGroovy DSLs - S2GForum London 2011 - Guillaume Laforge
Groovy DSLs - S2GForum London 2011 - Guillaume Laforge
 

Plus de Damien Seguy

Plus de Damien Seguy (20)

Qui a laissé son mot de passe dans le code
Qui a laissé son mot de passe dans le codeQui a laissé son mot de passe dans le code
Qui a laissé son mot de passe dans le code
 
Analyse statique et applications
Analyse statique et applicationsAnalyse statique et applications
Analyse statique et applications
 
Top 10 pieges php afup limoges
Top 10 pieges php   afup limogesTop 10 pieges php   afup limoges
Top 10 pieges php afup limoges
 
Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020
 
Meilleur du typage fort (AFUP Day, 2020)
Meilleur du typage fort (AFUP Day, 2020)Meilleur du typage fort (AFUP Day, 2020)
Meilleur du typage fort (AFUP Day, 2020)
 
Top 10 php classic traps confoo
Top 10 php classic traps confooTop 10 php classic traps confoo
Top 10 php classic traps confoo
 
Tout pour se préparer à PHP 7.4
Tout pour se préparer à PHP 7.4Tout pour se préparer à PHP 7.4
Tout pour se préparer à PHP 7.4
 
Top 10 php classic traps php serbia
Top 10 php classic traps php serbiaTop 10 php classic traps php serbia
Top 10 php classic traps php serbia
 
Top 10 php classic traps
Top 10 php classic trapsTop 10 php classic traps
Top 10 php classic traps
 
Top 10 chausse trappes
Top 10 chausse trappesTop 10 chausse trappes
Top 10 chausse trappes
 
Code review workshop
Code review workshopCode review workshop
Code review workshop
 
Understanding static analysis php amsterdam 2018
Understanding static analysis   php amsterdam 2018Understanding static analysis   php amsterdam 2018
Understanding static analysis php amsterdam 2018
 
Review unknown code with static analysis php ce 2018
Review unknown code with static analysis   php ce 2018Review unknown code with static analysis   php ce 2018
Review unknown code with static analysis php ce 2018
 
Everything new with PHP 7.3
Everything new with PHP 7.3Everything new with PHP 7.3
Everything new with PHP 7.3
 
Php 7.3 et ses RFC (AFUP Toulouse)
Php 7.3 et ses RFC  (AFUP Toulouse)Php 7.3 et ses RFC  (AFUP Toulouse)
Php 7.3 et ses RFC (AFUP Toulouse)
 
Tout sur PHP 7.3 et ses RFC
Tout sur PHP 7.3 et ses RFCTout sur PHP 7.3 et ses RFC
Tout sur PHP 7.3 et ses RFC
 
Review unknown code with static analysis php ipc 2018
Review unknown code with static analysis   php ipc 2018Review unknown code with static analysis   php ipc 2018
Review unknown code with static analysis php ipc 2018
 
Code review for busy people
Code review for busy peopleCode review for busy people
Code review for busy people
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonight
 
Machine learning in php las vegas
Machine learning in php   las vegasMachine learning in php   las vegas
Machine learning in php las vegas
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Strong typing @ php leeds

  • 1. PHP Leeds, Wales, United Kingdom Strong typing in PHP adoption, evolution and organisation
  • 2. AGENDA • PHPType hints syste m • Adoptio n • Evolutio n • Organisation
  • 3. SPEAKER • Damien Segu y • CTO @exaka t • Static analysis exper t • Retirement home for elePHPants
  • 4. Everyone uses typehinting 3 % 97 % With Typehints Without typehint
  • 7. Typehints as debug tactics • Set up a typehint • Wait for the 'Fatal error' • Fix the calling code, now that you know where it is • Remove it in production • Leave it in development <?php  foo("a"); foo(1); foo(new x); foo(array()); function foo(string $s) {     echo $s; } class x {     function __toString()  
 { return "a"; } } ?>
  • 8. Your code is already typed • Typehints are already used in the code • PHP, and strict_types • is_string(), is_array(), instanceof… • Coding conventions
  • 9. Coding conventions • The type is in the name of the argument • $string, $array • $user = new User(); <?php    function shorten($string) {       return substr($string, 0, 5); }    function getPattern(array $ints) {    } function (StringClass $string)  {    } ?>
  • 10. Moving type checks to the signature • is_a(), is_subclass_of(), instanceof, === null • is_string(), is_array() • (int), (string)… <?php   function bar($user) {     if ($user === null) {      throw new TypeError();    }      if (!$user instanceof User)) {       throw new TypeError();    }     return $user->validate();  }  ?>
  • 11. Moving type checks to the signature • is_a(), is_subclass_of(), instanceof, === null • is_string(), is_array() • (int), (string)… <?php   function bar(Usager $user) {      return $user->validate();  }  ?>
  • 12. Moving type checks to the signature • is_a(), is_subclass_of(), instanceof, === null • is_string(), is_array() • (int), (string)… <?php function bar($price) {       return floor((float) $price) * 1.21;   }   ?>
  • 13. Follow the lead <?php function bar($argument) {      return substr($argument, 0, 10); }   ?>
  • 14. Follow the lead <?php function bar(string $argument) {      return substr($argument, 0, 10); }   ?>
  • 15. Follow the lead <?php function bar($argument) : string {      return substr($argument, 0, 10); }   ?>
  • 16. Follow the lead <?php function bar(string $argument) : string {      return substr($argument, 0, 10) ?: ''; }   ?> Substr() returns string OR false N O T I N P H P 8 . 0 R C 1
  • 17.
  • 18. Backward with the return types <?php function bar($argument) {      return foo($argument); }   function foo($x) {      return barbar($x); }   function barbar($y) : string {  //... }   ?>
  • 19. Forward with caution <?php function bar3($argument) {      return foo(null); }   ?> <?php function bar($argument) {      return foo($argument); }   function foo($x) {      return barbar($x); }   function barbar(string $y) {  //... }   ?> <?php function bar2($argument) {      return foo(22); }   ?>
  • 20. Wait for PHP 8.0 <?php  function foo($x) {      if (rand(1, 3)) {      return 1;    }  else {      return barbar($x);    } }    function barbar($y) : string {   //... }    ?>
  • 21. Adoption • Use it for debugging purposes • Follow the types that are already there • PHP • Your framework • Propagate your own types • Return types are easy, argument types need caution
  • 23. Evolution • Typehints now have impact on your code • Wait for PHP 8.0 union types • Single type is a constraint and a tool
  • 24. Impact of defaults <?php  function foo($x = -1) {      if ($x === -1) {      return '';    }  else {      return substr($x, 0, 1);   } }    ?>
  • 25. Impact of defaults <?php class foo {   const DEFAULT = -1;   private $bar = self::DEFAULT;   public function foo() {       if ($this->bar === DEFAULT) {       return '';     }  else {       return substr($this->bar, 0, 1);    }  }     ?>
  • 26. Ambiguous cases <?php    function foo($b) {     return array_fill(0, 10, $b);   }   function bar($a) {     return shell_exec($a);   } ?>
  • 27. Ambiguous cases <?php     declare(strict_types = 1); function foo(array $a) { } foo(['a', 'b', 'c', 'd' ]); foo(['a', 'b', 'c', null, 2]); ?> • array() • No generic in PHP • Use attributes and 
 annotations
  • 28. Dubious cases <?php     declare(strict_types = 1); class x { function __set($name, $a) { //.. . } } $x = (new x); $x->c = 3; ?>
  • 29. Fossilisation stage C2 extends C1 C1 M1() M1() • Method signatures • Arguments count • Compulsory versus optional • Type • Default values • Visibility
  • 30. Fossilisation stage • Modify M1() in C3 • Modify M1() in C1 • Modify M1() in C2 and C4 • Modify M1() in C5 • Modify M1() in C6 • … C2 C1 C3 C4 C5 C6
  • 32. Evolution 0 % 17,5 % 35 % 52,5 % 70 % object iterable callable int bool void string array scalar Classes
  • 33. Evolution • Scalar types cannot evolve • Classes can evolve • Class types don't need to be complex • A price is not an int/ fl oat • A path may be a string while a string is not a path
  • 35. No types Evolution f1 ($a) : s f2 ($a) : s f3 ($a) : s f5 ($a) : s f4 ($a) : s ($a) : s f
  • 36. Also no types Evolution f1 ($a) : s f2 ($a) : s f3 ($a) : s f5 ($a) : s f4 ($a) : s ($a) : s f
  • 37. Evolution f1 ($a) : s f2 ($a) : s f3 ($a) : s f5 ($a) : s f4 ($a) : s ($a) : s f
  • 38. • Type hints reduces the number of possible paths in the code • Scalar are versatile • They have a lot of connectivity • Upgrading scalar types to class types reduce complexity even more Scalar types to classes Evolution f1 ($a) : s f2 ($a) : s f3 ($a) : s f5 ($a) : s f4 ($a) : s ($a) : s f
  • 40. Organisation • Typehinting has impact on the signature of a method • This impact spreads all over the application • It introduces a hierarchy of the classes
  • 41. Classes order Organisation • A method returns one type • A method has dependencies on its arguments's type • That object must be created fi rst • A method has dependencies on its constructor too C1 M1() __construct()
  • 42. Classes order Organisation • A method returns one type • A method has dependencies on its arguments's type • That object must be created fi rst • A method has dependencies on its constructor too C1 M1()
  • 43. Classes order Organisation C5 C1 C3 C2 • Mysql (C1) • Host/Login/Pwd (C2) • Prepare (M1) • Query (C3) C1 M1()
  • 44. Classes order Organisation C5 C1 C3 C2 • Mysql (C1) • Host/Login/Pwd (C2) • Prepare (M1) • Query (C3) C5 C1 C3 C2 C5 C1 C3 C2 C5 C1 C3 C2
  • 45. Classes order Organisation • Topological sorting of the classes • One class has priority over another class when it is used as typehint • There is no garantee for a single top class : • Probably several top classes • With scalar as argument, because they are so easy to tweak C5 C1 C3 C2
  • 48. Subsidiary questions Organisation • Why are there multiple methods with the same typehints? • Potential double work • How testable are the classes? • How many objects do you need to create an instance? • Can a method reach a speci fi c type of class? • The needed types may not be available
  • 49. Adding typehints to your code base • Adoption • Follow the current code • Evolution • Refactor the code, use classes as typehints • Organisation • Use typehints to reduce complexity and plan evolutions
  • 50. Subsidiary questions Static analysis helps you type • Exakat • Typehint suggestion report, type inconsistencies and typehint report • Phpdoctor • Reports missing types • Psalm • Infers typehints on the fl y
  • 51. Subsidiary questions Static analysis helps you type • Exakat • Typehint suggestion report, type inconsistencies and typehint report • Phpdoctor • Reports missing types • Psalm • Infers typehints on the fl y
  • 52. https://www.exakat.io/ | @exakat O, diolch yn fawr iawn
  • 53. Classes order Organisation M1 M2 C1 M1() __construct() M2() • M1 needs a property • M2 provides that property • M2 > M1() • True in PHP 7.4+ • x::$a must not be accessed before initialization • True in PHP 7.0 • Call to a member function bar() on null