Upgrade to Pro — share decks privately, control downloads, hide ads and more …

OOP - Day 2

Brian Fenton
September 16, 2009

OOP - Day 2

Part two of a two part tutorial on object-oriented programming in PHP that I gave to the KU Web Developer community

Brian Fenton

September 16, 2009
Tweet

More Decks by Brian Fenton

Other Decks in Programming

Transcript

  1. Quick Refresher/Warm-up •  Design a User class •  What properties

    should it have? •  What methods? – Including getters/setters •  What are some likely child classes?
  2. Abstract Classes/Methods •  Flags a class/method as “incomplete” •  Classes

    w/abstract method(s) must be abstract •  Instantiating an abstract class throws a PHP error •  Examples
  3. Interfaces •  A list of methods a class must have

    •  Uses “implements” keyword •  Preferred way to do type hinting •  Can define properties/constants too •  Example •  HoneyJar implements BearFood!
  4. Overriding methods •  Child classes can redefine parent methods – Depends

    on visibility •  Can call original version with parent::methodName()!
  5. Overloading methods •  Defining multiple methods with the same name,

    but accepting different arguments •  Not natively supported in PHP •  To fake it, use func_get_args()!
  6. Final keyword •  Prevents a method from being changed in

    child classes •  Can also apply to a class as a whole – This is the only way to make properties final •  Not very common •  Example
  7. Magic methods •  Start with __, like __construct()! •  Called

    automatically when certain things happen •  Examples: – __toString()! – __get() and __set()! – __clone()! – __sleep() and __wakeup()!
  8. Exceptions •  Errors as objects – Native PHP errors or user-defined

    –  throw new Exception();! •  Allows use of try/catch blocks •  SPL adds new Exception types •  ErrorException object
  9. Static keyword •  Adds functionality directly to a class itself

    •  Doesn’t require instantiation to use •  No access to $this! •  Can make things harder to test •  Example – ArrayUtils – Session::start()!
  10. Class autoloading •  Define function(s) to tell PHP where to

    find undefined classes •  Can define multiple functions with spl_autoload_register()! •  Zend or PEAR naming conventions – Bear_Polar lives at Bear\Polar.php on the file system
  11. Testing object equality •  $a = $b! – Create a reference

    •  $a == $b! – Type compare only •  $a === $b! – Do $a and $b point to the exact same object •  instanceof! – Tests “is, extends, or implements” – if ($dt instanceof DateTime) {…}!
  12. Object cloning •  How to actually copy an object – 

    $a = $b just makes a reference –  $a = clone($b) makes an actual new object •  __clone() magic method
  13. Object serialization •  Convert an object to a string for

    storage •  Commonly used when storing objects in a session file or a db •  “object” or “document” databases like MongoDB use this heavily •  serialize() / unserialize()! –  __sleep() and __wakeup()!
  14. Example PHP core objects •  Easy – SimpleXML – DateTime •  More

    powerful/complex – DomDocument – PDO •  Honorable mention – mysqli
  15. Best Practices - Documentation •  Learn and use the PHP

    Docblock syntax •  Annotations are becoming more popular/ powerful •  IDEs use this info to help you – Can also generate skeleton docs for you •  PHPDocumentor
  16. Dependency Inversion/Injection •  Don’t look for things, ask for them

    – If your class need a db connection, make it a required constructor argument •  Makes code easier to modify/test •  Dependencies are explicit
  17. Design Patterns •  Widely-accepted solutions to common problems – Often language-neutral

    (i.e. steal from Java) •  Anti-patterns/“code smells” – “You fell for one of the classic blunders”
  18. Example Design Patterns •  Examples – Factory (and Factory Method) – Value

    Object – ActiveRecord •  Example anti-pattern – God Class
  19. Polymorphism •  Behavior determined by class/subclass – Using same method name,

    just different implementations •  Simplifies logic, better encapsulation •  Example – From Wikipedia: polymorphism.php – DataWriter
  20. Unit Testing •  Writing tests (in PHP) to verify your

    code •  Test the smallest possible chunks (units) of code •  Test for results, not implementation •  Every requirement/bug should have tests •  PHPUnit – Most IDEs can build test skeletons for you
  21. Final exam! •  Design a blog using OO principles • 

    Requirements: – Users must be authenticated to submit content – Comments are allowed – Produce a list of the most recent 10 entries
  22. Final exam! •  Write a simple Database Abstraction Layer (DBAL)

    •  Requirements: – Supports Oracle and MySQL – Supports bound query parameters – Can fetch, add, update, and remove records – Implements the ExampleDBAL interface
  23. Resources •  The gold standard for OO code: –  http://en.wikipedia.org/wiki/Solid_%28object-

    oriented_design%29 •  PHPUnit –  http://www.phpunit.de (it’s in English) •  PHPDocumentor –  http://www.phpdoc.org/ •  Code Complete 2 –  An actual book, and a massive one at that •  http://www.phpfreaks.com/tutorial/oo-php-part-2- boring-oo-principles –  This covers a lot of the SOLID stuff in more detail