A Gentle Introduction to
 Object Oriented PHP
       Central Florida PHP




                             1
A Gentle Introduction to
Object Oriented PHP
• OOP: A Paradigm Shift
• Basic OO Concepts
• PHP4 vs. PHP5
• Case Study: Sim...
OOP: A Paradigm Shift




                        3
Procedural Code vs. Object
Oriented Code


• Procedural code is linear.
• Object oriented code is modular.




           ...
Procedural Code vs. Object
Oriented Code
  mysql_connect();
  mysql_select_db();

  $sql = “SELECT name FROM users ”;
  $s...
Procedural Code vs. Object
Oriented Code


  $User = new User;
  $row = $User->find(‘id=5’,‘name’);
  echo $row[‘name’];

...
Procedural Code vs. Object
Oriented Code

  1. <?php
  2.
  3. echo “Hello, World!”;
  4.
  5. ?>




                    ...
Procedural Code vs. Object
Oriented Code
         Email            LineItems        ZebraStripes
    + $to             + $...
When Procedural is Right


• Small bite-sized chunks
• Lightweight “Front End” code
• Sequential scripts




             ...
When OO is Right


• Large, enterprise-level applications.
• “Back-end” related code for heavy lifting.




              ...
The OO Mindset
• Flexibility is essential
  • “Code for an interface, not an implementation.”
• Everything has a pattern
•...
Basic OO Concepts




                    12
Classes & Objects

• Classes are templates
  class   Email {
    var   $to;
    var   $from;
    var   $subject;
    var  ...
Classes & Objects

• Objects are instances
  $one     =   new   Email;
  $two     =   new   Email;
  $three   =   new   Em...
Classes & Objects

• Classes are templates
  • A structured “shell” for a custom data type.
  • A class never executes.
• ...
Properties & Methods

• Properties describe an object
  $one = new Email;
  $one->to = ‘mike@example.com’;
  $one->from = ...
Properties & Methods


• Methods are actions an object can make
  $one->setFormat(‘text/plain’);
  $one->addAttachment(‘vi...
Properties & Methods

• Properties describe an object
 • Variables that are local to an object
• Methods are actions an ob...
Constructors
• One of many “magic” methods that PHP
  understands.
• Runs immediately upon object instantiation.
  class G...
Constructors
• Parameters may also be passed to a
  constructor during instantiation
  class Person {
    function __const...
Destructors
• Another “magic” method understood by
  PHP (there are lots of these guys, btw).
• Automatically called when ...
Inheritance

• Establishes a hierarchy between a parent
  class and a child class.
• Child classes inherit all visible mem...
Inheritance
  class Parent {
    function __construct() {
      echo “I am Papa Bear.”;
    }
  }
  class Child extends Pa...
Inheritance

• When a child class defines a method that
  exists in a parent class, it overrides its
  parent.
• A parent m...
Finality

• Inheritance may be prevented by declaring
  a class or method “final”
• Any attempt to extend or override a fina...
Visibility

  class PPP {
    public $a = ‘foo’;
    private $b = ‘bar’;
    protected $c = ‘baz’;

      public function ...
Visibility


 • Class members may be listed as
  • Public
  • Private
  • Protected




                                  ...
Visibility

 • Public members are visible in from
   anywhere.
  • Global Scope
  • Any Class’ Scope
 • The var keyword is...
Visibility


 • Private members are visible only to
   members of the same class.
 • Viewing or editing from outside of $t...
Visibility


 • Protected members are visible within $this
   or any descendant
 • Any public access of a protected member...
Static Members


• Members that are bound to a class, not an
  object.
• A static member will maintain value
  through all...
Static Members
  class Counter {
    public static $i;
    public function count() {
      self::$i++;
      return self::...
Static Members

• When referencing a static member, $this is
  not available.
  • From outside the class, ClassName::$memb...
PHP4 vs. PHP5




                34
PHP4 OOP


• No visibility
  • Everything is assumed public
• Objects passed by value, not by reference.




             ...
PHP5 OOP
• Completely rewritten object model.
• Visibility
• Objects passed by reference, not by value.
• Exceptions
• Int...
Case Study: Simplifying
      Requests



                          37
Understanding the Problem

• Request data is stored within several rather
  verbose superglobals
  • $_GET[‘foo’], $_GET[‘...
Understanding the Problem

• Their naming convention is nice, but...
  • Associative arrays don’t play well with quoted
  ...
The UML

                                                     File
          RequestHandler         + $name : String
- $da...
Homework

• Write an HTML generation library
 • Generates valid XHTML elements
 • Generates valid XHTML attributes
 • Know...
Suggested Reading
• PHP 5 Objects, Patterns, and Practice
  Matt Zandstra, Apress
• Object-Oriented PHP Concepts,
  Techni...
Upcoming SlideShare
Loading in …5
×

A Gentle Introduction To Object Oriented Php

8,877 views
8,673 views

Published on

Published in: Technology
2 Comments
12 Likes
Statistics
Notes
No Downloads
Views
Total views
8,877
On SlideShare
0
From Embeds
0
Number of Embeds
244
Actions
Shares
0
Downloads
524
Comments
2
Likes
12
Embeds 0
No embeds

No notes for slide

A Gentle Introduction To Object Oriented Php

  1. 1. A Gentle Introduction to Object Oriented PHP Central Florida PHP 1
  2. 2. A Gentle Introduction to Object Oriented PHP • OOP: A Paradigm Shift • Basic OO Concepts • PHP4 vs. PHP5 • Case Study: Simplifying Requests • Homework • Suggested Reading 2
  3. 3. OOP: A Paradigm Shift 3
  4. 4. Procedural Code vs. Object Oriented Code • Procedural code is linear. • Object oriented code is modular. 4
  5. 5. Procedural Code vs. Object Oriented Code mysql_connect(); mysql_select_db(); $sql = “SELECT name FROM users ”; $sql .= “WHERE id = 5 ”; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); echo $row[‘name’]; 5
  6. 6. Procedural Code vs. Object Oriented Code $User = new User; $row = $User->find(‘id=5’,‘name’); echo $row[‘name’]; 6
  7. 7. Procedural Code vs. Object Oriented Code 1. <?php 2. 3. echo “Hello, World!”; 4. 5. ?> 7
  8. 8. Procedural Code vs. Object Oriented Code Email LineItems ZebraStripes + $to + $taxPercent + $switch + $subject + $total + $normalClass + $message + addLine() + stripe() + __construct() + getTax() + send() + getGrandTotal() XHTMLTag HTMLEmail - $tag + $headers - $content - __construct() + __construct() + send() + __destruct() 8
  9. 9. When Procedural is Right • Small bite-sized chunks • Lightweight “Front End” code • Sequential scripts 9
  10. 10. When OO is Right • Large, enterprise-level applications. • “Back-end” related code for heavy lifting. 10
  11. 11. The OO Mindset • Flexibility is essential • “Code for an interface, not an implementation.” • Everything has a pattern • Everything is an Object • Iterate fast. Test often. • Smaller is better. 11
  12. 12. Basic OO Concepts 12
  13. 13. Classes & Objects • Classes are templates class Email { var $to; var $from; var $subject; var $message; } 13
  14. 14. Classes & Objects • Objects are instances $one = new Email; $two = new Email; $three = new Email; $four = new Email; $five = new Email; $six = new Email; 14
  15. 15. Classes & Objects • Classes are templates • A structured “shell” for a custom data type. • A class never executes. • Objects are instances • A “living” copy of a class. • A class executes (if you tell it to). 15
  16. 16. Properties & Methods • Properties describe an object $one = new Email; $one->to = ‘mike@example.com’; $one->from = ‘joe@example.com’; $one->subject = ‘Test’; $one->message = ‘Can you see me?’; 16
  17. 17. Properties & Methods • Methods are actions an object can make $one->setFormat(‘text/plain’); $one->addAttachment(‘virus.exe’); $one->send(); 17
  18. 18. Properties & Methods • Properties describe an object • Variables that are local to an object • Methods are actions an object can make • Functions that are local to an object • Have full access to any member in it’s scope (aka: $this). 18
  19. 19. Constructors • One of many “magic” methods that PHP understands. • Runs immediately upon object instantiation. class Gump { function __construct() { echo “Run Forrest! Run!”; } } 19
  20. 20. Constructors • Parameters may also be passed to a constructor during instantiation class Person { function __construct($name) { echo “Hi. I am $name.”; } } $me = new Person(‘Mike’); 20
  21. 21. Destructors • Another “magic” method understood by PHP (there are lots of these guys, btw). • Automatically called when an object is cleared from memory class Kaboom { function __destruct() { echo “Cheers. It’s been fun!”; } } 21
  22. 22. Inheritance • Establishes a hierarchy between a parent class and a child class. • Child classes inherit all visible members of it’s parent. • Child classes extend a parent class’ functionality. 22
  23. 23. Inheritance class Parent { function __construct() { echo “I am Papa Bear.”; } } class Child extends Parent { function __construct() { echo “I am Baby Bear.”; } } 23
  24. 24. Inheritance • When a child class defines a method that exists in a parent class, it overrides its parent. • A parent member may be accessed via the “scope resolution operator” parent::memberName() parent::$memberName; 24
  25. 25. Finality • Inheritance may be prevented by declaring a class or method “final” • Any attempt to extend or override a final entity will result in a fatal error • Think before you use this 25
  26. 26. Visibility class PPP { public $a = ‘foo’; private $b = ‘bar’; protected $c = ‘baz’; public function setB($newA) { // code... } } 26
  27. 27. Visibility • Class members may be listed as • Public • Private • Protected 27
  28. 28. Visibility • Public members are visible in from anywhere. • Global Scope • Any Class’ Scope • The var keyword is an alias for public 28
  29. 29. Visibility • Private members are visible only to members of the same class. • Viewing or editing from outside of $this will result in a parse error. 29
  30. 30. Visibility • Protected members are visible within $this or any descendant • Any public access of a protected member results in a parse error. 30
  31. 31. Static Members • Members that are bound to a class, not an object. • A static member will maintain value through all instances of its class. 31
  32. 32. Static Members class Counter { public static $i; public function count() { self::$i++; return self::$i; } } echo Counter::count(); echo Counter::count(); 32
  33. 33. Static Members • When referencing a static member, $this is not available. • From outside the class, ClassName::$member; • From inside the class, self::$member; • From a child class, parent::$member; 33
  34. 34. PHP4 vs. PHP5 34
  35. 35. PHP4 OOP • No visibility • Everything is assumed public • Objects passed by value, not by reference. 35
  36. 36. PHP5 OOP • Completely rewritten object model. • Visibility • Objects passed by reference, not by value. • Exceptions • Interfaces and Abstract Classes • ... 36
  37. 37. Case Study: Simplifying Requests 37
  38. 38. Understanding the Problem • Request data is stored within several rather verbose superglobals • $_GET[‘foo’], $_GET[‘bar’] • $_POST[‘baz’], $_POST[‘bang’] • $_FILES[‘goo’][‘tmp_name’] 38
  39. 39. Understanding the Problem • Their naming convention is nice, but... • Associative arrays don’t play well with quoted strings • Data is segrigated over several different arrays (this is both good and bad) • Programmers are lazy 39
  40. 40. The UML File RequestHandler + $name : String - $data : Array + $type : String + __construct() : Void + $size : Int - captureRequestData() : Void + $tmp_name : String - captureFileData() : Void + $error : Int + __get($var : String) : Mixed + __construct($file : Array) : Void + upload($destination : String) : Bool 40
  41. 41. Homework • Write an HTML generation library • Generates valid XHTML elements • Generates valid XHTML attributes • Knows how to self close elements w/no content • Post your code to our Google Group • groups.google.com/group/cfphp 41
  42. 42. Suggested Reading • PHP 5 Objects, Patterns, and Practice Matt Zandstra, Apress • Object-Oriented PHP Concepts, Techniques, and Code Peter Lavin, No Starch Press • The Pragmatic Programmer Andrew Hunt and David Thomas, Addison Wesley • Advanced PHP Programming George Schlossngale, Sams 42

×