Patterns and OOP in PHP George Schlossnagle. Patterns catalog solutions to categories of problems They consist of A name A description of their problem.

Slides:



Advertisements
Similar presentations
Understand and appreciate Object Oriented Programming (OOP) Objects are self-contained modules or subroutines that contain data as well as the functions.
Advertisements

©Ian Sommerville 2000 Software Engineering, 6th edition. Chapter 12Slide 1 Software Design l Objectives To explain how a software design may be represented.
Classes & Objects Computer Science I Last updated 9/30/10.
Object-Oriented PHP (1)
Reza Gorgan Mohammadi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Satzinger, Jackson, and Burd Object-Orieneted Analysis & Design
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Design Patterns.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Chapter 3.4 Programming Fundamentals. 2 Data Structures Arrays – Elements are adjacent in memory (great cache consistency) – They never grow or get reallocated.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Object-oriented design CS 345 September 20,2002. Unavoidable Complexity Many software systems are very complex: –Many developers –Ongoing lifespan –Large.
C++ fundamentals.
Programming Paradigms Imperative programming Functional programming Logic programming Event-driven programming Object-oriented programming A programming.
OOP Languages: Java vs C++
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
Programming Languages and Paradigms Object-Oriented Programming.
Design Patterns.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object-oriented programming and software development Lecture 1.
An Object-Oriented Approach to Programming Logic and Design
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Guided Notes Ch. 9 ADT and Modules Ch. 10 Object-Oriented Programming PHP support for OOP and Assignment 4 Term project proposal C++ and Java Designer.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
AN OBJECT LESSON IN CLASSES “or how OO ABL solves everything.”
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
Testing OO software. State Based Testing State machine: implementation-independent specification (model) of the dynamic behaviour of the system State:
Design Reuse Earlier we have covered the re-usable Architectural Styles as design patterns for High-Level Design. At mid-level and low-level, design patterns.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
ISBN Object-Oriented Programming Chapter Chapter
Copyright © 2005 Elsevier Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
(1) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
Written by: Dr. JJ Shepherd
1 CSE Programming in C++. 2 Overview Sign roster list Syllabus and Course Policies Introduction to C++ About Lab 1 Fill Questionnaire.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
OOP Basics Classes & Methods (c) IDMS/SQL News
Lecture 2 Intro. To Software Engineering and Object-Oriented Programming (2/2)
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Chapter 10 Design Patterns.
MPCS – Advanced java Programming
Low Budget Productions, LLC
Behavioral Design Patterns
OOP What is problem? Solution? OOP
Magento Technical Guidelines Eugene Shakhsuvarov, Software Magento
Advanced Programming Behnam Hatami Fall 2017.
Object-Oriented PHP (1)
GoF Patterns Ch. 26.
Presentation transcript:

Patterns and OOP in PHP George Schlossnagle

Patterns catalog solutions to categories of problems They consist of A name A description of their problem A description of the solution An assessment of the pros and cons of the pattern What are Patterns?

Not so much. Patterns sources outside OOP include: Architecture (the originator of the paradigm) User Interface Design (wizards, cookie crumbs, tabs) Cooking (braising, pickling) What do patterns have to do with OOP?

Brining Problem: Make lean meat jucier Solution: Submerge the meat in a salt and flavor infused liquid. Discussion: Salt denatures the meat proteins, allowing them to trap liquid between them more efficiently. Example: Mix 1C of table salt and 1C of molasses into 1G of water. Bring to a boil to dissolve. Submerge pork roast for 2 days. A tasty design pattern

OOP is paradigm more than a feature set. Everyone is a bit different, and they all think they're right The classic difference click(button) vs. button.click() What is OOP?

Let’s try to define OOP through the values it tries to promote. Allow compartmentalized refactoring of code Promote code reuse Promote extensability Is OOP the only solution for this? Of course not. Rephrase: What is its motivation?

Encapsulation is about grouping of related properties and operations into classes. Classes represent complex data types and the operations that act on them. An object is a particular instance of a class. For example ‘Dog’ may be a class (it’s a type of thing), while Grendel (my dog) is an instance of that class. Encapsulation

Classses as dictionaries are a common idiom, seen in C: typedef struct _entry { time_t date; char *data; char *(*display)(struct _entry *e); } entry; e->display(e); You can see this idiom in Perl and Python, both of which prototype class methods to explicitly grab $this (or their equivalent). Are Classes Just Dictionaries?

PHP is somewhat different, since PHP functions aren't really first class objects. Still, PHP4 objects were little more than arrays. The difference is coherency. Classes can be told to automatically execute specific code on object creation and destruction. class Simple { function __construct() {/*...*/} function __destruct() { /*...*/} } Are Classes Just Dictionaries?

Leaving a Legacy A class can specialize (or extend) another class and inherit all its methods, properties and behaviors. This promotes Extensibility Reusability Code Consolidation

A Simple Inheritance Example class Dog { public function __construct($name) {/*...*/} public function bark() { /*...*/ } public function sleep() { /*...*/} public function eat() { /*...*/} } class Rottweiller extends Dog { public function intimidate($person); }

Inheritance and the issue of Code Duplication Code duplication is a major problem for maintainability. You often end up with code that looks like this: function foo_to_xml($foo) { // generic stuff // foo-specific stuff } function bar_to_xml($bar) { // generic stuff // bar specific stuff }

The Problem of Code Duplication You could clean that up as follows: function base_to_xml($data) { /*...*/ } function foo_to_xml($foo) { base_to_xml($foo); // foo specific stuff } function bar_to_xml($bar) { base_to_xml($bar); // bar specific stuff } But it’s hard to keep base_to_xml() working for the disparate foo and bar types.

The Problem of Code Duplication In an OOP style you would create classes for the Foo and Bar classes that extend from a base class that handles common functionality. class Base { public function toXML() { /*...*/ } } class Foo extends Base { public function toXML() { parent::toXML(); // foo specific stuff } } class Bar extends Base { public function toXML() { parent::toXML(); // Barspecific stuff } } Sharing a base class promotes sameness.

Multiple inheritance is confusing. If you inherit from ClassA and ClassB, and they both define method foo(), whose should you inherit? Interfaces allow you to specify the functionality that your class must implement. Type hints allow you to require (runtime checked) that an object passed to a function implements or inherits certain required facilities. Multiple Inheritance

interface Displayable { public function display(); } class WeblogEntry implements Displayable { public function display() { /*...*/} } function show_stuff(Displayable $p) { $p->display(); } vs. function show_stuff($p) { if(method_exists($p, ‘display’)) { $p->display(); } } Problem is those checks need to be added in every function. Multiple Inheritance

Abstract classes provide you a cross between a ‘real’ class and an interface. They are classes where certain methods are defined, and other methods are only prototyped. Abstract classes are useful for providing a base class that should never be instantiated. abstract class CalendarEntry { abstract function display(); public function fetchDetails() { /*...*/} public function saveDetails() {/*...*/} } Abstract Classes

One of the notions of OOP is that your package/library should have a public API that users should interact with. What happens behind the scenes is none of their business, as long as this public API is stable. This separation is often referred to as ‘data hiding’ or ‘implementation hiding’. Some languages (Perl, Python) rely on a ‘gentleman’s contract’ to enforce this separation, while other languages enforce it as a language feature. Public Relations

PHP implements strict visibility semantics. Data hiding eases refactoring by controlling what other parties can access in your code. public anyone can access it protected only descendants can access it private only you can access it final no one can re-declare it. Why have these in PHP? Because sometimes self-discipline isn’t enough. Data Hiding

Suppose we have a calendar that is a collection of entries. Procedurally dislpaying all the entries might look like: foreach($entries as $entry) { switch($entry->type) { case 'professional': display_professional_entry($entry); break; case 'personal': display_personal_entry($entry); break; } } Minimizing Special Case Handling

In an OOP paradigm this would look like: foreach($entries as $entry) { $entry->display(); } The key point is we don't have to modify this loop to add new types. When we add a new type, that type gets a display() method so it know how to display itself, and we’re done. (p.s. this is a good case for the aggregate pattern, shown later) Simplicity Through Polymorphism

Weren’t we talking about patterns...?

Problem: You only want one instance of an object to ever exist at one time Solutions: PHP4: Use a factory method with static cache PHP4: Use a global cache and runtime instance mutability PHP5: Use static class attributes Singleton Pattern

Description: class Singleton { static private $instance; private function __construct() {} static public function instance() { if(!self::$instance) { self::$instance = new Singleton(); } return self::$instance; } } $s = Singleton::instance(); Singleton Pattern

Static properties and methods belong to a class as a whole, not a particular instance. To reference your own static properties, you use: $my_prop = self::$prop; Static properties are not inherited (they are compile-time resolved).To reference a parent’s property use: $dads_prop = parent::$prop; To reference an external classes property use: $class_prop = Class::$prop; PPP still applies! Static Properties and Methods

Problem: You have collections of items that you operate on frequently with lots of repeated code. Remember our calendars: foreach($entries as $entry) { $entry->display(); } Solution: Create a container that implements the same interface, and perfoms the iteration for you. Aggregator Pattern

class EntryAggregate extends Entry { protected $entries;... public function display() { foreach($this->entries as $entry) { $entry->display(); } public function add(Entry $e) { array_push($this->entries, $e); } } By extending Entry, the aggregate can actually stand in any place that entry did, and can itsefl contain other aggregated collections. Aggregator Pattern

Problem: You need to be able to iterate through an aggregation. Solution: Implement all the operations necessary to logically iterate over an object. In PHP this is now a built in facility so that object implementing the Iterator interface can be used in the language array constructs like foreach(). Iterator Pattern

An Infinite Iterator class EndlessSquares implements Iterator { private $idx = 0; function key() { return $this->idx; } function current() { return $this->idx * $this->idx; } function next() { $this->idx++; return $this; } function valid() { return true; } function rewind() { $this->idx = 0; } } es = new EndlessSquares; foreach($es as $square) { echo "$sq\n"; }

Why not just use: foreach($aggregate as $item) { /*...*/ } Aren't we making life more difficult than need be? No! For simple aggregations the above works fine, but not everything is an array. What about: Buffered result sets Directories Anything not already an array Aren’t Iterators Pointless in PHP?

Problem: You need to provide access to an object, but it has an interface you don’t know at compile time. Solution: Use accessor/method overloading to dynamically dispatch methods to the object. Discussion: This is very typical of RPC-type facilities like SOAP where you can interface with the service by reading in a definitions file of some sort at runtime. Proxy Pattern

class SOAP_Client { public $wsdl; public function __construct($endpoint) { $this->wsdl = WSDLManager::get($endpoint); } public function __call($method, $args) { $port = $this->wsdl->getPortForOperation($method); $this->endpoint = $this->wsdl->getPortEndpoint($port); $request = SOAP_Envelope::request($this->wsdl); $request->addMethod($method, $args); $data = $request->saveXML(); return SOAP_Envelope::parse($this->endpoint, $data); } } Proxy Pattern in PEAR SOAP

Problem: You want an object to automatically notify dependents when it is updated. Solution: Allow 'observer' to register themselves with the observable object. Discussion: An object may not apriori know who might be interested in it. The Observer pattern allows objects to register their interest and supply a notification method. Observer Pattern

class Observable { protected $observers; public function attach(Observer $o) { array_push($this->observers, $o); } public function notify() { foreach($this->observers as $o) { $o->update(); } } } interface Observer { public function update(); } Concrete Examples: logging facilities: , debugging, SOAP message notifications. NOT Apache request hooks. Observer Pattern

THANKS! Slides for this talk will be available shortly at A longer version with 3 hours of info and a greater focus on patterns and advanced features will be presented by Marcus Boerger and myself at OSCON in July. Come see us there! Shameless book plug: Buy my book, you’ll like it. I promise.