Type-Safe Objects in PHP

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Notes on slide 1

    Theme created by Sakari Koivunen and Henrik Omma Released under the LGPL license.

    12 Favorites & 1 Group

    Type-Safe Objects in PHP - Presentation Transcript

    1. Welcome! Type-Safe Objects in PHP Sebastian Bergmann http://sebastian-bergmann.de/ May 23 rd 2008
    2. Welcome! Type-Safe Objects in PHP Sebastian Bergmann http://sebastian-bergmann.de/ May 23 rd 2008
    3. Welcome! Type-Safe Properties in PHP Sebastian Bergmann http://sebastian-bergmann.de/ May 23 rd 2008
    4. Welcome! Type-Safe Properties in PHP Sebastian Bergmann http://sebastian-bergmann.de/ May 23 rd 2008
    5. Welcome! Of Type Safety, Properties, Annotations, Multiple Inheritance, and Traits Sebastian Bergmann http://sebastian-bergmann.de/ May 23 rd 2008
    6. Who I am
      • Sebastian Bergmann
      • Involved in the PHP Project since 2000
      • Developer of PHPUnit
      • Author, Consultant, Coach, Trainer
    7. Outline
      • What is type safety?
        • Static Typing vs. Dynamic Typing
        • Strong Typing vs. Weak Typing
        • Spoiler: PHP is not type-safe
          • But Java is not really type-safe, either :-) *
      * http://www.cis.upenn.edu/~bcpierce/courses/629/papers/Saraswat-javabug.html
    8. Outline
      • What is type safety?
        • Static Typing vs. Dynamic Typing
        • Strong Typing vs. Weak Typing
        • Spoiler: PHP is not type-safe
          • But Java is not really type-safe, either :-) *
      • Look at situations where type-safe properties for objects in PHP make sense
      * http://www.cis.upenn.edu/~bcpierce/courses/629/papers/Saraswat-javabug.html
    9. Outline
      • What is type safety?
        • Static Typing vs. Dynamic Typing
        • Strong Typing vs. Weak Typing
        • Spoiler: PHP is not type-safe
          • But Java is not really type-safe, either :-) *
      • Look at situations where type-safe properties for objects in PHP make sense
      • Implementing type-safe properties using
        • Annotations and
        • __get() and __set()
      * http://www.cis.upenn.edu/~bcpierce/courses/629/papers/Saraswat-javabug.html
    10. Type Safety
      • “A language is type-safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data.”
      Definition by Vijay Saraswat
    11. Type Safety
      • Static Typing
        • Enforcement of Type Safety at Compile-Time
          • Type associated with variable name upon declaration
        • Example Languages: C, C++, C#, Java
    12. Type Safety
      • Static Typing
        • Enforcement of Type Safety at Compile-Time
          • Type associated with variable name upon declaration
        • Example Languages: C, C++, C#, Java
      • Dynamic Typing
        • Enforcement of Type Safety at Runtime
          • Type associated with value upon creation
        • Example Languages: Lisp, PHP, Python, Smalltalk
    13. Type Safety
      • Strong Typing
        • Restrictions on the intermixing of types that is permitted to occur
        • Explicit casting from one type to another
        • Example Languages: C++, C#, Lisp, Java, Python
    14. Type Safety
      • Strong Typing
        • Restrictions on the intermixing of types that is permitted to occur
        • Explicit casting from one type to another
        • Example Languages: C++, C#, Lisp, Java, Python
      • Weak Typing
        • “Not Strong Typing”
          • Implicit casting from one type to another, for instance
        • Example Languages: C, JavaScript, PHP
    15. Type Safety in PHP <?php $variable = 'sebastian' ; Dynamic Typing
    16. Type Safety in PHP <?php $variable = 'sebastian'; $variable = 2204 ; Dynamic Typing
    17. Type Safety in PHP <?php $variable = 'sebastian'; $variable = 2204; $variable = array(); Dynamic Typing
    18. Type Safety in PHP <?php $variable = 'sebastian'; $variable = 2204; $variable = array(); $variable = new StdClass ; // ... Dynamic Typing
    19. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump ( 1 + 1 ); int(2)
    20. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump( 1 + 1 ); var_dump ( '1' + '1' ); int(2) int(2)
    21. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump( 1 + 1 ); var_dump('1' + '1'); class One { public function __toString () { return '1' ; } } var_dump (new One + new One ); int(2) int(2) Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 int(2)
    22. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump( 1 + 1 ); var_dump('1' + '1'); class Two { public function __toString () { return '2' ; } } var_dump (new Two + new Two ); int(2) int(2) Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 int(2)
    23. Type Safety in PHP Weak Typing: Explicit Type Conversion <?php var_dump( 1 + 1 ); var_dump('1' + '1'); class Two { public function __toString() { return '2'; } } var_dump ((string)new Two + (string)new Two ); int(2) int(2) int(4)
    24. Type Safety in PHP Type Hints <?php class Vector { public function add ( Vector $vector ) { // ... } } $x = new Vector ; $x -> add (new Vector );
    25. Type Safety in PHP Type Hints <?php class Vector { public function add ( $vector ) { if (!( $vector instanceof Vector )) { die( 'Argument must be a Vector object.' ); } // ... } } $x = new Vector ; $x -> add (new Vector );
    26. Type Safety in PHP Type Hints <?php class Vector { public function add ( Vector $vector ) { // ... } } $x = new Vector ; $x -> add (new Vector );
    27. Type Safety in PHP Type Hints <?php class Vector { public function add(Vector $vector) { // ... } } $x = new Vector; $x -> add (new StdClass ); Catchable fatal error: Argument 1 passed to Vector::add() must be an instance of Vector, instance of stdClass given, called in /tmp/test.php on line 11 and defined in /tmp/test.php on line 4
    28. Type Safety in PHP Type Hints
      • PHP 5.3 supports
        • array and class or interface names as argument type hints
        • no type hints for return values
    29. Type Safety in PHP Type Hints
      • PHP 5.3 supports
        • array and class or interface names as argument type hints
        • no type hints for return values
      • Future versions of PHP might support
        • type hints for scalar types ( string , int , ...)
        • type hints for return values
    30. Storing Data in Objects <?php class Employee { public $id ; public $name ; }
      • Attributes publicly accessible
        • Attributes are also called fields or slots sometimes
      • No enforcement of value types
      Public Attributes
    31. Storing Data in Objects <?php class Employee { protected $id ; protected $name ; public function getId () { return $this -> id ; } public function setId ( $id ) { if ( is_int ( $id )) { $this -> id = $id ; } else { throw new InvalidArgumentException ; } } // ... }
      • Attributes not directly accessible
      • Enforcement of value types in setter methods
      Protected Attributes and Accessor Methods
    32. Storing Data in Objects <?php class Employee { protected $id ; protected $name ; public function getId () { return $this -> id ; } public function setId ( $id ) { if ( is_int ( $id )) { $this -> id = $id ; } else { // ... } } // ... }
      • Attributes not directly accessible
      • Enforcement of value types in setter methods
        • But attributes might still be (unintentionally) accessed directly from “within”
      Protected Attributes and Accessor Methods
    33. Storing Data in Objects <?php class Employee { protected $id ; protected $name ; public function getId () { return $this -> id ; } public function setId ( $id ) { if ( is_int ( $id )) { $this -> id = $id ; } else { // ... } } // ... }
      • Attributes not directly accessible
      • Enforcement of value types in setter methods
        • But attributes might still be (unintentionally) accessed directly from “within”
      • No syntactic relationship between the attribute and the methods that manage it
      Protected Attributes and Accessor Methods
    34. Storing Data in Objects <?php class Employee { protected $id ; protected $name ; public function getId () { return $this -> id ; } public function setId ( $id ) { if ( is_int ( $id )) { $this -> id = $id ; } else { // ... } } // ... }
      • Attributes not directly accessible
      • Enforcement of value types in setter methods
        • But attributes might still be (unintentionally) accessed directly from “within”
      • No syntactic relationship between the attribute and the methods that manage it
      • These methods have to be called explicitly by the accessing context
      Protected Attributes and Accessor Methods
    35. Storing Data in Objects Properties
      • Construct in languages such as C# or Delphi
        • Just like an attribute, but access is automatically translated into method calls
        • Use Cases
          • Type Checking
          • Bounds Checking
          • Read-Only Attributes
          • Persistence
          • ...
    36. Storing Data in Objects Properties
      • Construct in languages such as C# or Delphi
        • Just like an attribute, but access is automatically translated into method calls
        • Use Cases
          • Type Checking
          • Bounds Checking
          • Read-Only Attributes
          • Persistence
          • ...
      • Can be implemented in PHP using the __get() , __set() , and __isset() interceptors
        • This is an idiom used in the eZ Components
    37. Interlude eZ Components
      • Provide a solid platform for PHP application development
      • Clean and simple API
      • Excellent documentation
      • Keep backward compatibility for longer periods of time
      • Stable and few regressions
      • Clean IP, Open Source friendly
      • http://ezcomponents.org/
    38. Properties The eZ Components Way <?php class Employee { protected $properties = array( 'id' => NULL , 'name' => NULL ); public function __get ( $name ) { switch ( $name ) { case 'id' : case 'name' : { return $this -> properties [ $name ]; } } throw new ezcBasePropertyNotFoundException ( $name ); } // ... }
    39. Properties The eZ Components Way <?php class Employee { public function __set ( $name , $value ) { switch ( $name ) { case 'id' : { if ( is_int ( $value )) { $this -> properties [ $name ] = $value ; } } break; // ... } throw new ezcBasePropertyNotFoundException ( $name ); } // ... }
    40. Properties The eZ Components Way <?php class Employee { // ... public function __isset ( $name ) { switch ( $name ) { case 'id' : case 'name' : { return TRUE ; } } return FALSE ; } }
    41. Type-Safe Properties <?php class Employee { /** * @var integer */ protected $id ; /** * @var string */ protected $name ; }
      • By now we are used to annotate attribute declarations with type information
        • This metadata is used, for instance, by PHPDocumentor to generate API documentation
      Annotations
    42. Type-Safe Properties <?php class Employee { /** * @var integer */ protected $id ; /** * @var string */ protected $name ; }
      • By now we are used to annotate attribute declarations with type information
        • This metadata is used, for instance, by PHPDocumentor to generate API documentation
        • But it is also usefull when we want to automatically generate SQL queries or WSDL from an object
      Annotations
    43. Type-Safe Properties <?php class Employee { /** * @var integer */ protected $id ; /** * @var string */ protected $name ; }
      • By now we are used to annotate attribute declarations with type information
        • This metadata is used, for instance, by PHPDocumentor to generate API documentation
        • But it is also usefull when we want to automatically generate SQL queries or WSDL from an object
      • PHP allows read access to these docblocks at runtime through its Reflection API
        • So let us use this metadata for reusable __get() and __set() implementations
      Annotations
    44. Interlude <?php class Employee { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $class = new ReflectionClass ( 'Employee' ); $attributes = $class -> getProperties (); foreach ( $attributes as $attribute ) { $docComment = $attribute -> getDocComment (); if ( preg_match ( '/@var[s]+([.w]+)/' , $docComment , $matches )) { var_dump ( $matches [ 1 ]); } } Annotations and the Reflection API
    45. Type-Safe Properties <?php abstract class TypeSafeObject { protected $annotationsParsed = FALSE ; protected $properties = array(); protected function parseAnnotations () { if (! $this -> annotationsParsed ) { $class = new ReflectionClass ( $this ); $attributes = $class -> getProperties (); foreach ( $attributes as $attribute ) { $docComment = $attribute -> getDocComment (); if ( preg_match ( '/@var[s]+([.w]+)/' , $docComment , $matches )) { $this -> properties [ $attribute -> getName ()] = array( 'type' => $matches [ 1 ], 'value' => NULL ); } } $this -> annotationsParsed = TRUE ; } } // ... The TypeSafeObject Class
    46. Type-Safe Properties public function __get ( $name ) { $this -> parseAnnotations (); if ( isset ( $this -> properties [ $name ])) { return $this-> properties [ $name ][ 'value' ]; } else { // ... } } The TypeSafeObject Class
    47. Type-Safe Properties public function __get($name) { $this->parseAnnotations(); if (isset($this->properties[$name])) { return $this->properties[$name]['value']; } else { // ... } } public function __set ( $name , $value ) { $this -> parseAnnotations (); if ( isset ( $this -> properties [ $name ]) ) { if ( gettype ( $value ) == $this -> properties [ $name ][ 'type' ]) { $this -> properties [ $name ][ 'value' ] = $value ; } else { // ... } } else { // ... } } // ... The TypeSafeObject Class
    48. Type-Safe Properties public function __isset ( $name ) { $this -> parseAnnotations (); return isset ( $this -> properties [ $name ]); } } The TypeSafeObject Class
    49. Type-Safe Properties <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id ; /** * @var string */ protected $name ; } Using the TypeSafeObject Class
    50. Type-Safe Properties <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $e = new Employee ; var_dump ( $e -> id ); NULL Using the TypeSafeObject Class
    51. Type-Safe Properties <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $e = new Employee; $e -> id = '123' ; var_dump ( $e -> id ); NULL Using the TypeSafeObject Class
    52. Type-Safe Properties <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $e = new Employee; $e -> id = 123 ; var_dump ( $e -> id ); int(123) Using the TypeSafeObject Class
    53. Type-Safe Properties <?php abstract class TypeSafeObject { // ... } class Employee extends TypeSafeObject { /** * @var integer */ protected $id ; /** * @var string */ protected $name ; } Problems with the TypeSafeObject Class
      • Conceptual problem
        • Employee is a TypeSafeObject
    54. Type-Safe Properties <?php abstract class TypeSafeObject { // ... } class Person extends TypeSafeObject { // ... } class Employee extends Person { /** * @var integer */ protected $id; /** * @var string */ protected $name; } Problems with the TypeSafeObject Class
      • Conceptual problem
        • Employee is a TypeSafeObject
        • This usually does not fit into our model
    55. Type-Safe Properties <?php abstract class TypeSafeObject { // ... } class Person extends TypeSafeObject { // ... } class Employee extends Person { /** * @var integer */ protected $id; /** * @var string */ protected $name; } Problems with the TypeSafeObject Class
      • Conceptual problem
        • Employee is a TypeSafeObject
        • This usually does not fit into our model
      • PHP 5.3 supports
        • Single Implementation Inheritance
        • Multiple Interface Inheritance
    56. Type-Safe Properties <?php trait TypeSafeObject { // ... } class Person { use TypeSafeObject ; // ... } class Employee extends Person { /** * @var integer */ protected $id; /** * @var string */ protected $name; } Traits to the rescue!
      • Conceptual problem
        • Employee is a TypeSafeObject
        • This usually does not fit into our model
      • PHP 5.3 supports
        • Single Implementation Inheritance
        • Multiple Interface Inheritance
      • Future versions of PHP will support Traits
        • Safe variant of multiple implementation inheritance
          • A class can implement multiple interfaces
          • A class can extend a single class
          • A class can use multiple traits
        • Reuse sets of methods freely in several independent classes living in different class hierarchies
    57. Inheritance
      • Single Inheritance
        • A class can inherit interface and implementation from a single parent class
    58. Inheritance
      • Single Inheritance
        • A class can inherit interface and implementation from a single parent class
      • Interfaces
        • A class can inherit interface and implementation from a single parent class
        • A class can implement multiple interfaces
    59. Inheritance
      • Single Inheritance
        • A class can inherit interface and implementation from a single parent class
      • Interfaces
        • A class can inherit interface and implementation from a single parent class
        • A class can implement multiple interfaces
      • Multiple Inheritance
        • A class can inherit interface and implementation from multiple parent classes
    60. Multiple Inheritance
      • A class has contradicting goals
        • Generator of Instances
          • Must be complete
          • Must have a unique place in the class hierarchy
        • Unit of Reuse
          • Should be small
          • Should be applicable at arbitrary places
      Problems
    61. Multiple Inheritance
      • A class has contradicting goals
        • Generator of Instances
          • Must be complete
          • Must have a unique place in the class hierarchy
        • Unit of Reuse
          • Should be small
          • Should be applicable at arbitrary places
      • “Multiple inheritance is good, but there is no good way to do it.” (Steve Cook)
        • Example: The Diamond Problem
      Problems
    62. Multiple Inheritance The Diamond Problem class A { public function method () { } }
      • Class A declares method()
    63. Multiple Inheritance The Diamond Problem class A { public function method() { } } class B extends A { public function method () { } } class C extends A { public function method () { } }
      • Class A declares method()
      • Classes B and C inherit from A and override method() differently
    64. Multiple Inheritance The Diamond Problem class A { public function method() { } } class B extends A { public function method() { } } class C extends A { public function method() { } } class D extends B , C { }
      • Class A declares method()
      • Classes B and C inherit from A and override method() differently
      • Class D inherits from both B and C and does not override method()
    65. Multiple Inheritance The Diamond Problem class A { public function method() { } } class B extends A { public function method() { } } class C extends A { public function method() { } } class D extends B, C { } $d = new D ; $d -> method ();
      • Class A declares method()
      • Classes B and C inherit from A and override method() differently
      • Class D inherits from both B and C and does not override method()
      • When we call method() on an object of D , which implementation should be called?
    66. Traits
      • New unit of reuse
        • Provide structure, modularity and reusability within classes
        • Can be incomplete
    67. Traits
      • New unit of reuse
        • Provide structure, modularity and reusability within classes
        • Can be incomplete
      • Less complex than Multiple Inheritance
        • The typical problems associated with multiple inheritance (as well as mixins) are avoided
    68. Traits
      • New unit of reuse
        • Provide structure, modularity and reusability within classes
        • Can be incomplete
      • Less complex than Multiple Inheritance
        • The typical problems associated with multiple inheritance (as well as mixins) are avoided
      • Flattening Property
        • Traits are flattened into classes at compile-time
        • No notion of traits at runtime
    69. Resources
      • Libraries
        • https://labs.omniti.com/trac/alexandria/browser/trunk/OmniTI/Object.php
          • Annotation-based, Type-Safe Properties
          • Support for Mix-In Inheritance
        • http://jan.kneschke.de/projects/typesafe-objects-in-php
          • Annotation-based, Type-Safe Properties
          • Automatic generation of SQL and WSDL
        • http://instantsvc.sourceforge.net/
          • Extended Reflection API
          • Automatic generation of WSDL
      • Traits
        • http://wiki.php.net/rfc/traits
          • Background Information
          • Specification and Patch for implementation in C for PHP
    70. The End
      • Thank you for your interest!
      • These slides will be available shortly on http://sebastian-bergmann.de/talks/.
    71. License
      • This presentation material is published under the Attribution-Share Alike 3.0 Unported license.
      • You are free:
          • to Share – to copy, distribute and transmit the work.
          • to Remix – to adapt the work.
      • Under the following conditions:
          • Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).
          • Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license.
      • For any reuse or distribution, you must make clear to others the license terms of this work.
      • Any of the above conditions can be waived if you get permission from the copyright holder.
      • Nothing in this license impairs or restricts the author's moral rights.

    + Sebastian BergmannSebastian Bergmann, 2 years ago

    custom

    7967 views, 12 favs, 13 embeds more stats

    Out-of-the-Box, PHP does not support the declaratio more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 7967
      • 7143 on SlideShare
      • 824 from embeds
    • Comments 0
    • Favorites 12
    • Downloads 0
    Most viewed embeds
    • 616 views on http://sebastian-bergmann.de
    • 138 views on http://www.planet-php.net
    • 34 views on http://www.planet-php.org
    • 16 views on http://planet-php.org
    • 6 views on http://www.phpeye.com

    more

    All embeds
    • 616 views on http://sebastian-bergmann.de
    • 138 views on http://www.planet-php.net
    • 34 views on http://www.planet-php.org
    • 16 views on http://planet-php.org
    • 6 views on http://www.phpeye.com
    • 6 views on http://lj-toys.com
    • 2 views on http://www.xianguo.com
    • 1 views on http://www.theinquirer.de
    • 1 views on applewebdata://848ED1FE-2DF6-403A-AA8D-C5555B9621A8
    • 1 views on http://www.xaprb.com
    • 1 views on file://
    • 1 views on http://planet-php.net
    • 1 views on http://www.activars.com

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories

    Groups / Events