SlideShare une entreprise Scribd logo
1  sur  42
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Tendances (20)

PHP slides
PHP slidesPHP slides
PHP slides
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
C lab-programs
C lab-programsC lab-programs
C lab-programs
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
Practical Spherical Harmonics Based PRT Methods
Practical Spherical Harmonics Based PRT MethodsPractical Spherical Harmonics Based PRT Methods
Practical Spherical Harmonics Based PRT Methods
 
php
phpphp
php
 
Quick sort
Quick sortQuick sort
Quick sort
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
hidden surface elimination using z buffer algorithm
hidden surface elimination using z buffer algorithmhidden surface elimination using z buffer algorithm
hidden surface elimination using z buffer algorithm
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Introduction to MPI
Introduction to MPIIntroduction to MPI
Introduction to MPI
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 

En vedette

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.
 

En vedette (20)

Php Oop
Php OopPhp Oop
Php Oop
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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 Takeoffsammart93
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Dernier (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

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