fowa expo08

56
PHP5 For an easy coding life Keir Whitaker - Carsonified Future of Web Apps Expo London 2008

Upload: keir-whitaker

Post on 14-Dec-2014

1.069 views

Category:

Technology


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Fowa Expo08

PHP5 For an easy coding lifeKeir Whitaker - Carsonified

Future of Web Apps Expo London 2008

Page 2: Fowa Expo08

Welcome to FOWAThanks for coming

Page 3: Fowa Expo08

Who am I?My name is Keir and I work at Carsonified

Started with HTML 4 in 1999

Progressed to ASP in 2000

Managed web projects for large East London NHS trust

Freelance developer from 2005 - 2008 using ASP.Net, MS SQL, MySQL and PHP

Joined Carsonified in 2008

Help with our web projects and events

Co-developed a Twitter mash up called MATT using Django

Page 4: Fowa Expo08

And you are? Say hello :)

Page 5: Fowa Expo08

What we’ll look at todayDevelopment environments

From PHP4 to PHP5

Classes and Object Orientated Programming

MVC = Model View Controller

CRUD & Models

SMARTY

Requests and Responses

Third party code - some examples

Simple XML and API’s

Page 6: Fowa Expo08

Development EnvironmentsChoosing the right tools

Page 7: Fowa Expo08

Useful ToolsCode Editor (It’s personal)

Mac - TextMate, DreamWeaver, SKEdit

PC - DreamWeaver, UltraEdit, NotePad

MySQL

PHP MyAdmin (web based)

Mac - CocoaMySQL

FTP Client

Mac - Transmit, SecureFTP (FREE)

PC - Cute FTP, FileZilla (FREE)

Local Server Environment

Mac - MAMP/MAMP Pro

PC - WAMP Server

Source Control

Subversion, Git and a host of toerhs

Useful Add Ons

Web developer toolbar Firefox

Firebug for AJAX development

Page 8: Fowa Expo08

From PHP4 to PHP5 Here’s how I use to develop in PHP4

Functions, functions and more functions

Little thought to how functions could relate to each other

Lots of included files in php files in lots of different directories

The occasional use of a class (usually from the web)

Little or no separation of code, content and presentation

Small changes = lots of work as I needed to edit multiple files

Page 9: Fowa Expo08

From PHP4 to PHP5Here’s how I develop now using PHP5

One PHP file above the server root

Clear seperation between content and presentation

Heavy use of Object Orientated Programming

SMARTY Template Engine (OK it’s PHP4!)

Classes to handle interaction with MySQL

Simplified inclusion of third party code

Easier to manage, easier to code, easier life!

Page 10: Fowa Expo08

Code Demo #1Procedural programming with PHP4

Page 11: Fowa Expo08

Classes and OOPWhat’s all the fuss about?

Page 12: Fowa Expo08

What is OOP?

Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including encapsulation, modularity, polymorphism, and inheritance. It was not commonly used in mainstream software application development until the early 1990s. Many modern programming languages now support OOP.

- http://en.wikipedia.org/wiki/Object_oriented

Page 13: Fowa Expo08

So what does that mean?OOP allows us to create reusable chunks of code and keep our code DRY (Don’t Repeat Yourself)

Modularise our applications functionality

Allow to code to interact in a safe way

Keep code and presentation seperate

Easily extend our applications

Page 14: Fowa Expo08

Classes & ObjectsA class is a “blueprint” for an object.

A class merely describes a “type” of object

Before you can use a class you need to

Create an “object” based on the class. Once created this is called a “class instance”

To do this you “instantiate” the class

Once “instantiated” you can call the methods defined in that class (methods are just functions)

Page 15: Fowa Expo08

What’s in a class?Classes USUALLY contain

Methods

These are PHP functions. No real difference to writing a standard PHP function. They can take arguments and return values.

Class methods have access to a special variable called “$this”

Variables for use within the class

NB: It’s important to understand that variables can vary from “instance” to “instance”. This is what makes classes so valuable.

Page 16: Fowa Expo08

What’s in a class? cont...Classes MAY contain

A Constructor

This is used to set up the class in some way at the point of instantiation

They do not have a return value

A Destructor

This is automagically called when the class is “destroyed”. It’s available but not often used in practice.

Page 17: Fowa Expo08

Code Demo #2A basic PHP5 class

Page 18: Fowa Expo08

Always return valuesAvoid output in classes

e.g. don’t use echo and printf

It reduces flexibility

Return values via the class

This allows further transformations to be undertaken or the value could be used in a different way entirely. For example in an e-mail

Page 19: Fowa Expo08

Understanding scope Variable scope

Global

Function

Class

It’s easy to get caught out

With OOP you tend to only use the Class scope

Page 20: Fowa Expo08

What is $this-> all about?$this is a special variable

Used all the time in PHP5 classes

It refers to a particular instance of a class

Used to call methods and get/set variables in that instance

Page 21: Fowa Expo08

Code Demo #3Understanding $this

Page 22: Fowa Expo08

Visibility in classesThe visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private

Public declared items can be accessed everywhere

Protected limits access to inherited and parent classes (and to the class that defines the item)

Private limits visibility only to the class that defines the item

This affects how you interact with a class instance

i.e. how you get and set variables and call methods

Page 23: Fowa Expo08

Code Demo #4Understanding visibility

Page 24: Fowa Expo08

InheritanceClasses can inherit functionality and variables from other classes

Allows us to extend the functionality of one class without changing it

e.g.

extending a data access class to add paging

Giving all your classes access to a number of “base” functions used on every section of your site

Extend a “base controller” - more later

Page 25: Fowa Expo08

Code Demo #5Class inheritance

Page 26: Fowa Expo08

PHP5 AutoloadingFact: Your code needs to know where your classes are in the file system

This usually requires using the require_once(path_to_file) function to include the file

If we stick to conventions we can avoid having to remember to include our class files every time

Page 27: Fowa Expo08

Code Demo #6Auto loading

Page 28: Fowa Expo08

MVC Model View Controller

Page 29: Fowa Expo08

What is MVC?MVC = Model, View, Controller

It’s an “architectural pattern”

Popular PHP MVC type frameworks include Cake PHP, Code Igniter, Zend and Symfony

For our purposes here’s a definition

Model

A way of interacting with a data model, usually incorporates the data access layer which allows us to manipulate our database contents

View

The visual representation of the request and/or model data

Controller

A device to process requests and determine what actions should be taken

Page 30: Fowa Expo08

What’s the point?Clean separation of concerns

Loosely coupled components

Easier to manage

Different team members can handle different part of the project

Page 31: Fowa Expo08

Our approach for todayModel

Our own classes extended from a basic MySQL class

View

Smarty Template Engine

Controller

Custom class to handle requests and responses

.htaccess

Page 32: Fowa Expo08

CRUD & ModelsRolling our own models

Page 33: Fowa Expo08

Extending our MySQL ClassModel making

New classes based on distinct data requirements

e.g. a Post model, a comment model or a user model

Make it handle all CRUD actions

CReate

Update

Delete

Write once and use often

Return usable numeric based PHP arrays, transform them later if needed

Page 34: Fowa Expo08

Code Demo #7Making a model

Page 35: Fowa Expo08

SMARTYUsing a template engine to handle our views

Page 36: Fowa Expo08

What is SMARTY?SMARTY is a PHP template engine

It allows us to separate our PHP code from HTML

It has a wealth of helpful plugins to make our lives easier and those of our designer colleagues

It’s as quick as PHP code as it’s compiled the first time it is run

It offers features such as caching

It’s written in PHP4 but that’s not a problem

Page 37: Fowa Expo08

Flexibility and re-useWe can adhere to DRY but we want flexibility as things change

What common templates could we have

HTML Header

HTML Footer

Main content

Sidebar

How do we deal with page titles and different CSS and JavaScript files?

SMARTY variables to the rescue

Page 38: Fowa Expo08

Code Demo #8Using SMARTY

Page 39: Fowa Expo08

Requests & ResponsesUsing a controller

Page 40: Fowa Expo08

URL != Real FileMVC enables us to move away from the idea that a URL is a representation of a file on a server

It enables us to create clean and hackable URLs (Flickr is a great example of this)

Advantages

We move away from the page paradigm - URLs are not directly linked to a folder structure

Easy to manage and integrate new functionality

Disadvantages

Need to find a way to process requests and work out what to do

We need to delve into the world of mod_rewrite!

Page 41: Fowa Expo08

.htaccess and mod_rewrite.htaccess

.htaccess files (or "distributed configuration files") provide a way to make server configuration changes

- http://httpd.apache.org/docs/1.3/howto/htaccess.html

mod_rewrite

The Swiss Army Knife of URL manipulation!

It provides a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly

Our rewrite rules are placed in our .htaccess file

Page 42: Fowa Expo08

Requests• Request flow

1.User requests a URL (e.g. /photos/users/keir)

2.Our .htaccess file looks to see if there is a match in the rewrite rules

1.If YES it calls the page with querystring parameters defined in the rewrite rule

2.If NO it returns a 404 Page Not Found

Page 43: Fowa Expo08

Rewrite rule exampleThe following rule will match if the URL = /about/ or /about

RewriteRule ^about/?$ /controller.php?action=displayAboutPage [NC,L]

It will request the file /controller.php?action=displayAboutPage

[NC, L] = Non Case Sensitive, Last rule - stop processing

Page 44: Fowa Expo08

Cheat sheetmod_rewrite cheat sheet

http://www.addedbytes.com/apache/mod_rewrite-cheat-sheet/

Page 45: Fowa Expo08

What’s next?mod_rewrite -> controller.php

A controller works out what to display based on querystring parameters (or lack) of from your rewrite rule

It’s just a PHP5 class

It can hook in SMARTY, ask for and receive data and display templates depending on the arguments it receives

It effectively brokers your “request” and processes your “response”

The “response” could be to display a template, send an email or even redirect to another site

It’s an approach designed to be flexible

Page 46: Fowa Expo08

Code Demo #9Processing a request with a controller

Page 47: Fowa Expo08

One controller fits allFront Controller

Much easier if one controller worked for our entire project

We could:

Create a controller that worked out which controller and action to call

Have all controllers extend the “base controllers” functionality which lightens our coding load

A “base controller” could be responsible for setting up our db connection, our SMARTY connection and our variables etc.

Page 48: Fowa Expo08

Code Demo #10Creating a front and base controller

Page 49: Fowa Expo08

Third party codeExamples of useful php classes

Page 50: Fowa Expo08

Open Source ClassesGood examples of open source classes

Flickr API wrappers - http://www.flickr.com/services/api/

FreindFeed - http://friendfeed.com/api/

Akismet (Spam protection) - http://www.achingbrain.net/stuff/php/akismet

SimplePie (RSS & ATOM Parser) - http://simplepie.org/

PHP Mailer (E-mail!) - http://phpmailer.codeworxtech.com/

Page 51: Fowa Expo08

SimpleXMLHandling XML in PHP5

Page 52: Fowa Expo08

SimpleXML LibraryPHP5 introduced SimpleXML

Makes it very easy to handle XML

No external libraries needed

Ability to use XPath to query XML

e.g $xml->xpath("//bookmarks/bookmark")

Page 53: Fowa Expo08

Code Demo #11SimpleXML & grabbing data from API’s

Page 54: Fowa Expo08

Code Demo #12Lifestream app overview

Page 55: Fowa Expo08

Thanks http://twitter.com/keirwhitaker

http://www.fiveandlime.com

Page 56: Fowa Expo08

That’s all folks :)I hope you enjoyed it and see you at the show!