Fowa Expo08

Post on 14-Dec-2014

1,067 views 2 download

description

 

transcript

PHP5 For an easy coding lifeKeir Whitaker - Carsonified

Future of Web Apps Expo London 2008

Welcome to FOWAThanks for coming

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

And you are? Say hello :)

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

Development EnvironmentsChoosing the right tools

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

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

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!

Code Demo #1Procedural programming with PHP4

Classes and OOPWhat’s all the fuss about?

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

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

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)

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.

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.

Code Demo #2A basic PHP5 class

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

Understanding scope Variable scope

Global

Function

Class

It’s easy to get caught out

With OOP you tend to only use the Class scope

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

Code Demo #3Understanding $this

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

Code Demo #4Understanding visibility

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

Code Demo #5Class inheritance

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

Code Demo #6Auto loading

MVC Model View Controller

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

What’s the point?Clean separation of concerns

Loosely coupled components

Easier to manage

Different team members can handle different part of the project

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

CRUD & ModelsRolling our own models

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

Code Demo #7Making a model

SMARTYUsing a template engine to handle our views

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

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

Code Demo #8Using SMARTY

Requests & ResponsesUsing a controller

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!

.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

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

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

Cheat sheetmod_rewrite cheat sheet

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

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

Code Demo #9Processing a request with a controller

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.

Code Demo #10Creating a front and base controller

Third party codeExamples of useful php classes

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/

SimpleXMLHandling XML in PHP5

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

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

Code Demo #12Lifestream app overview

Thanks http://twitter.com/keirwhitaker

http://www.fiveandlime.com

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