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

Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4jrouwe
 
Pitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYPitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYAnaya Medias Swiss
 
Normalização - Alexandruk
Normalização - AlexandrukNormalização - Alexandruk
Normalização - AlexandrukHebert Alquimim
 
Tutorial - Criando Banco com MySQL Workbench
Tutorial - Criando Banco com MySQL WorkbenchTutorial - Criando Banco com MySQL Workbench
Tutorial - Criando Banco com MySQL WorkbenchDaniel Brandão
 
Programando em python interfaces graficas com tk
Programando em python   interfaces graficas com tkProgramando em python   interfaces graficas com tk
Programando em python interfaces graficas com tksamuelthiago
 
Estrutura de Dados em Java (Funções e Procedimentos)
Estrutura de Dados em Java (Funções e Procedimentos)Estrutura de Dados em Java (Funções e Procedimentos)
Estrutura de Dados em Java (Funções e Procedimentos)Adriano Teixeira de Souza
 
Lógica de Programação com Javascript - Aula #04
Lógica de Programação com Javascript - Aula #04Lógica de Programação com Javascript - Aula #04
Lógica de Programação com Javascript - Aula #04Ramon Kayo
 

Mais procurados (8)

Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4
 
Pitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYPitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONY
 
Normalização - Alexandruk
Normalização - AlexandrukNormalização - Alexandruk
Normalização - Alexandruk
 
Tutorial - Criando Banco com MySQL Workbench
Tutorial - Criando Banco com MySQL WorkbenchTutorial - Criando Banco com MySQL Workbench
Tutorial - Criando Banco com MySQL Workbench
 
POO - 21 - Java e Banco de Dados
POO - 21 - Java e Banco de DadosPOO - 21 - Java e Banco de Dados
POO - 21 - Java e Banco de Dados
 
Programando em python interfaces graficas com tk
Programando em python   interfaces graficas com tkProgramando em python   interfaces graficas com tk
Programando em python interfaces graficas com tk
 
Estrutura de Dados em Java (Funções e Procedimentos)
Estrutura de Dados em Java (Funções e Procedimentos)Estrutura de Dados em Java (Funções e Procedimentos)
Estrutura de Dados em Java (Funções e Procedimentos)
 
Lógica de Programação com Javascript - Aula #04
Lógica de Programação com Javascript - Aula #04Lógica de Programação com Javascript - Aula #04
Lógica de Programação com Javascript - Aula #04
 

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

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

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Último (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

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