SlideShare uma empresa Scribd logo
1 de 42
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep DiveMartijn Dashorst
 
C* Summit 2013: How Not to Use Cassandra by Axel Liljencrantz
C* Summit 2013: How Not to Use Cassandra by Axel LiljencrantzC* Summit 2013: How Not to Use Cassandra by Axel Liljencrantz
C* Summit 2013: How Not to Use Cassandra by Axel LiljencrantzDataStax Academy
 
remote-method-guesser - BHUSA2021 Arsenal
remote-method-guesser - BHUSA2021 Arsenal remote-method-guesser - BHUSA2021 Arsenal
remote-method-guesser - BHUSA2021 Arsenal Tobias Neitzel
 
[PHP 也有 Day #64] PHP 升級指南
[PHP 也有 Day #64] PHP 升級指南[PHP 也有 Day #64] PHP 升級指南
[PHP 也有 Day #64] PHP 升級指南Shengyou Fan
 
Reverse proxies & Inconsistency
Reverse proxies & InconsistencyReverse proxies & Inconsistency
Reverse proxies & InconsistencyGreenD0g
 
XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?Yurii Bilyk
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developersPatrick Savalle
 
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB
 
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
 
Cross site scripting
Cross site scriptingCross site scripting
Cross site scriptingkinish kumar
 
User administration without you - integrating LDAP
User administration without you - integrating LDAPUser administration without you - integrating LDAP
User administration without you - integrating LDAPMongoDB
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keywordPham Huy Tung
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMMin-Yih Hsu
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMarlon Jamera
 
SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기OnGameServer
 
The innerHTML Apocalypse
The innerHTML ApocalypseThe innerHTML Apocalypse
The innerHTML ApocalypseMario Heiderich
 

Mais procurados (20)

Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep Dive
 
Json
JsonJson
Json
 
C* Summit 2013: How Not to Use Cassandra by Axel Liljencrantz
C* Summit 2013: How Not to Use Cassandra by Axel LiljencrantzC* Summit 2013: How Not to Use Cassandra by Axel Liljencrantz
C* Summit 2013: How Not to Use Cassandra by Axel Liljencrantz
 
remote-method-guesser - BHUSA2021 Arsenal
remote-method-guesser - BHUSA2021 Arsenal remote-method-guesser - BHUSA2021 Arsenal
remote-method-guesser - BHUSA2021 Arsenal
 
[PHP 也有 Day #64] PHP 升級指南
[PHP 也有 Day #64] PHP 升級指南[PHP 也有 Day #64] PHP 升級指南
[PHP 也有 Day #64] PHP 升級指南
 
Reverse proxies & Inconsistency
Reverse proxies & InconsistencyReverse proxies & Inconsistency
Reverse proxies & Inconsistency
 
API Basics
API BasicsAPI Basics
API Basics
 
XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
 
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
 
Cross site scripting
Cross site scriptingCross site scripting
Cross site scripting
 
User administration without you - integrating LDAP
User administration without you - integrating LDAPUser administration without you - integrating LDAP
User administration without you - integrating LDAP
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVM
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Pentesting jwt
Pentesting jwtPentesting jwt
Pentesting jwt
 
SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기
 
The innerHTML Apocalypse
The innerHTML ApocalypseThe innerHTML Apocalypse
The innerHTML Apocalypse
 

Destaque

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.
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais 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
 

Mais 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
 

Último

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Último (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

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