SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
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: Simplifying Requests
• Homework
• Suggested Reading


                                     2
OOP: A Paradigm Shift




                        3
Procedural Code vs. Object
Oriented Code


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




                                     4
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
Procedural Code vs. Object
Oriented Code


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




                                       6
Procedural Code vs. Object
Oriented Code

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




                             7
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
When Procedural is Right


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




                                 9
When OO is Right


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




                                               10
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
Basic OO Concepts




                    12
Classes & Objects

• Classes are templates
  class   Email {
    var   $to;
    var   $from;
    var   $subject;
    var   $message;
  }




                          13
Classes & Objects

• Objects are instances
  $one     =   new   Email;
  $two     =   new   Email;
  $three   =   new   Email;
  $four    =   new   Email;
  $five    =   new   Email;
  $six     =   new   Email;




                              14
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
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
Properties & Methods


• Methods are actions an object can make
  $one->setFormat(‘text/plain’);
  $one->addAttachment(‘virus.exe’);
  $one->send();




                                           17
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
Constructors
• One of many “magic” methods that PHP
  understands.
• Runs immediately upon object instantiation.
  class Gump {
    function __construct() {
      echo “Run Forrest! Run!”;
    }
  }



                                                19
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
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
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
Inheritance
  class Parent {
    function __construct() {
      echo “I am Papa Bear.”;
    }
  }
  class Child extends Parent {
    function __construct() {
      echo “I am Baby Bear.”;
    }
  }


                                 23
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
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
Visibility

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

      public function setB($newA) {
        // code...
      }
  }



                                      26
Visibility


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




                                    27
Visibility

 • Public members are visible in from
   anywhere.
  • Global Scope
  • Any Class’ Scope
 • The var keyword is an alias for public



                                            28
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
Visibility


 • Protected members are visible within $this
   or any descendant
 • Any public access of a protected member
   results in a parse error.




                                                30
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
Static Members
  class Counter {
    public static $i;
    public function count() {
      self::$i++;
      return self::$i;
    }
  }

  echo Counter::count();
  echo Counter::count();


                                32
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
PHP4 vs. PHP5




                34
PHP4 OOP


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




                                               35
PHP5 OOP
• Completely rewritten object model.
• Visibility
• Objects passed by reference, not by value.
• Exceptions
• Interfaces and Abstract Classes
• ...


                                               36
Case Study: Simplifying
      Requests



                          37
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
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
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
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

CSS_Day_Three (W3schools)
CSS_Day_Three (W3schools)CSS_Day_Three (W3schools)
CSS_Day_Three (W3schools)Rafi Haidari
 
モダンmod_perl入門 #yapcasia
モダンmod_perl入門 #yapcasiaモダンmod_perl入門 #yapcasia
モダンmod_perl入門 #yapcasia鉄次 尾形
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Overview of Vulnerability Scanning.pptx
Overview of Vulnerability Scanning.pptxOverview of Vulnerability Scanning.pptx
Overview of Vulnerability Scanning.pptxAjayKumar73315
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Elizabeth alexander
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Footprinting and reconnaissance
Footprinting and reconnaissanceFootprinting and reconnaissance
Footprinting and reconnaissanceNishaYadav177
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionMikhail Egorov
 
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)Marco Balduzzi
 
Object oriented vs. object based programming
Object oriented vs. object based  programmingObject oriented vs. object based  programming
Object oriented vs. object based programmingMohammad Kamrul Hasan
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...Simplilearn
 

Was ist angesagt? (20)

CSS_Day_Three (W3schools)
CSS_Day_Three (W3schools)CSS_Day_Three (W3schools)
CSS_Day_Three (W3schools)
 
モダンmod_perl入門 #yapcasia
モダンmod_perl入門 #yapcasiaモダンmod_perl入門 #yapcasia
モダンmod_perl入門 #yapcasia
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Php array
Php arrayPhp array
Php array
 
Overview of Vulnerability Scanning.pptx
Overview of Vulnerability Scanning.pptxOverview of Vulnerability Scanning.pptx
Overview of Vulnerability Scanning.pptx
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Footprinting and reconnaissance
Footprinting and reconnaissanceFootprinting and reconnaissance
Footprinting and reconnaissance
 
Type Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLikeType Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLike
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protection
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
 
Object oriented vs. object based programming
Object oriented vs. object based  programmingObject oriented vs. object based  programming
Object oriented vs. object based programming
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
 

Andere mochten auch

Login and Registration form using oop in php
Login and Registration form using oop in phpLogin and Registration form using oop in php
Login and Registration form using oop in phpherat university
 
Introduction to PHP OOP
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOPfakhrul hasan
 
BUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESSBUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESSPRINCE KUMAR
 
Dropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHPDropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHPelliando dias
 
Ejobportal project ppt on php my_sql
Ejobportal project ppt on php my_sqlEjobportal project ppt on php my_sql
Ejobportal project ppt on php my_sqlprabhat kumar
 
Lan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHPLan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHPAman Soni
 
Zend Php Certification Study Guide
Zend Php Certification Study GuideZend Php Certification Study Guide
Zend Php Certification Study GuideKamalika Guha Roy
 
Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in phpChetan Patel
 
Web School - School Management System
Web School - School Management SystemWeb School - School Management System
Web School - School Management Systemaju a s
 
OOP Basic - PHP
OOP Basic - PHPOOP Basic - PHP
OOP Basic - PHPSulaeman .
 
Php login system with admin features evolt
Php login system with admin features   evoltPhp login system with admin features   evolt
Php login system with admin features evoltGIMT
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Edu ware school management system software
Edu ware school management system softwareEdu ware school management system software
Edu ware school management system softwareArth InfoSoft P. Ltd.
 
PHP Technical Questions
PHP Technical QuestionsPHP Technical Questions
PHP Technical QuestionsPankaj Jha
 

Andere mochten auch (20)

Php Oop
Php OopPhp Oop
Php Oop
 
Login and Registration form using oop in php
Login and Registration form using oop in phpLogin and Registration form using oop in php
Login and Registration form using oop in php
 
Introduction to PHP OOP
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOP
 
Beginning OOP in PHP
Beginning OOP in PHPBeginning OOP in PHP
Beginning OOP in PHP
 
Oops
OopsOops
Oops
 
BUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESSBUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESS
 
Dropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHPDropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHP
 
Ejobportal project ppt on php my_sql
Ejobportal project ppt on php my_sqlEjobportal project ppt on php my_sql
Ejobportal project ppt on php my_sql
 
Lan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHPLan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHP
 
Zend Php Certification Study Guide
Zend Php Certification Study GuideZend Php Certification Study Guide
Zend Php Certification Study Guide
 
PHP based School ERP
PHP based School ERPPHP based School ERP
PHP based School ERP
 
Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in php
 
Web School - School Management System
Web School - School Management SystemWeb School - School Management System
Web School - School Management System
 
OOP Basic - PHP
OOP Basic - PHPOOP Basic - PHP
OOP Basic - PHP
 
Php login system with admin features evolt
Php login system with admin features   evoltPhp login system with admin features   evolt
Php login system with admin features evolt
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Edu ware school management system software
Edu ware school management system softwareEdu ware school management system software
Edu ware school management system software
 
Practice exam php
Practice exam phpPractice exam php
Practice exam php
 
PHP Technical Questions
PHP Technical QuestionsPHP Technical Questions
PHP Technical Questions
 

Ähnlich wie A Gentle Introduction To Object Oriented Php

Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHPRob Knight
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsSergio Acosta
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
PHP Development With MongoDB
PHP Development With MongoDBPHP Development With MongoDB
PHP Development With MongoDBFitz Agard
 
PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)MongoSF
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterZendCon
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Workhorse Computing
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Rabble .
 
PHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxPHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxAtikur Rahman
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
 
PHPID online Learning #6 Migration from procedural to OOP
PHPID online Learning #6 Migration from procedural to OOPPHPID online Learning #6 Migration from procedural to OOP
PHPID online Learning #6 Migration from procedural to OOPAchmad Mardiansyah
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceJesse Vincent
 
Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Chris Tankersley
 

Ähnlich wie A Gentle Introduction To Object Oriented Php (20)

Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
 
Magic methods
Magic methodsMagic methods
Magic methods
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and Bindings
 
Python advance
Python advancePython advance
Python advance
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
PHP Development With MongoDB
PHP Development With MongoDBPHP Development With MongoDB
PHP Development With MongoDB
 
PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
PHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxPHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptx
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
PHPID online Learning #6 Migration from procedural to OOP
PHPID online Learning #6 Migration from procedural to OOPPHPID online Learning #6 Migration from procedural to OOP
PHPID online Learning #6 Migration from procedural to OOP
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
 
Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016
 

Mehr von Michael Girouard

Day to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerDay to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerMichael Girouard
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptMichael Girouard
 
JavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsJavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsMichael Girouard
 
JavaScript From Scratch: Events
JavaScript From Scratch: EventsJavaScript From Scratch: Events
JavaScript From Scratch: EventsMichael Girouard
 
JavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataJavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataMichael Girouard
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetMichael Girouard
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Michael Girouard
 
Learning To Love Java Script
Learning To Love Java ScriptLearning To Love Java Script
Learning To Love Java ScriptMichael Girouard
 
Learning To Love Java Script Color
Learning To Love Java Script ColorLearning To Love Java Script Color
Learning To Love Java Script ColorMichael Girouard
 

Mehr von Michael Girouard (17)

Day to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerDay to Day Realities of an Independent Worker
Day to Day Realities of an Independent Worker
 
Responsible JavaScript
Responsible JavaScriptResponsible JavaScript
Responsible JavaScript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Ajax for PHP Developers
Ajax for PHP DevelopersAjax for PHP Developers
Ajax for PHP Developers
 
JavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsJavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script Applications
 
JavaScript From Scratch: Events
JavaScript From Scratch: EventsJavaScript From Scratch: Events
JavaScript From Scratch: Events
 
JavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataJavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With Data
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet Wet
 
Its More Than Just Markup
Its More Than Just MarkupIts More Than Just Markup
Its More Than Just Markup
 
Web Standards Evangelism
Web Standards EvangelismWeb Standards Evangelism
Web Standards Evangelism
 
A Look At Flex And Php
A Look At Flex And PhpA Look At Flex And Php
A Look At Flex And Php
 
Baking Cakes With Php
Baking Cakes With PhpBaking Cakes With Php
Baking Cakes With Php
 
Cfphp Zce 01 Basics
Cfphp Zce 01 BasicsCfphp Zce 01 Basics
Cfphp Zce 01 Basics
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
Learning To Love Java Script
Learning To Love Java ScriptLearning To Love Java Script
Learning To Love Java Script
 
Learning To Love Java Script Color
Learning To Love Java Script ColorLearning To Love Java Script Color
Learning To Love Java Script Color
 

Kürzlich hochgeladen

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 SavingEdi Saputra
 
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 FMESafe Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
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.pdfsudhanshuwaghmare1
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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, Adobeapidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
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 AmsterdamUiPathCommunity
 
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 educationjfdjdjcjdnsjd
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 

Kürzlich hochgeladen (20)

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
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

A Gentle Introduction To Object Oriented Php

  • 1. A Gentle Introduction to Object Oriented PHP Central Florida PHP 1
  • 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
  • 4. Procedural Code vs. Object Oriented Code • Procedural code is linear. • Object oriented code is modular. 4
  • 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. Procedural Code vs. Object Oriented Code $User = new User; $row = $User->find(‘id=5’,‘name’); echo $row[‘name’]; 6
  • 7. Procedural Code vs. Object Oriented Code 1. <?php 2. 3. echo “Hello, World!”; 4. 5. ?> 7
  • 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. When Procedural is Right • Small bite-sized chunks • Lightweight “Front End” code • Sequential scripts 9
  • 10. When OO is Right • Large, enterprise-level applications. • “Back-end” related code for heavy lifting. 10
  • 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
  • 13. Classes & Objects • Classes are templates class Email { var $to; var $from; var $subject; var $message; } 13
  • 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. 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. 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. Properties & Methods • Methods are actions an object can make $one->setFormat(‘text/plain’); $one->addAttachment(‘virus.exe’); $one->send(); 17
  • 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. Constructors • One of many “magic” methods that PHP understands. • Runs immediately upon object instantiation. class Gump { function __construct() { echo “Run Forrest! Run!”; } } 19
  • 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. 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. 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. Inheritance class Parent { function __construct() { echo “I am Papa Bear.”; } } class Child extends Parent { function __construct() { echo “I am Baby Bear.”; } } 23
  • 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. 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. Visibility class PPP { public $a = ‘foo’; private $b = ‘bar’; protected $c = ‘baz’; public function setB($newA) { // code... } } 26
  • 27. Visibility • Class members may be listed as • Public • Private • Protected 27
  • 28. Visibility • Public members are visible in from anywhere. • Global Scope • Any Class’ Scope • The var keyword is an alias for public 28
  • 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. Visibility • Protected members are visible within $this or any descendant • Any public access of a protected member results in a parse error. 30
  • 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. Static Members class Counter { public static $i; public function count() { self::$i++; return self::$i; } } echo Counter::count(); echo Counter::count(); 32
  • 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
  • 35. PHP4 OOP • No visibility • Everything is assumed public • Objects passed by value, not by reference. 35
  • 36. PHP5 OOP • Completely rewritten object model. • Visibility • Objects passed by reference, not by value. • Exceptions • Interfaces and Abstract Classes • ... 36
  • 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. 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. 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. 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. 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