Some Doctrine 2 Best Practices

Doctrine 2 has a very powerful database abstraction layer and features an Object Relational Mapper (ORM) that makes it very easy to manage relationships between the data in your application and provides tools that aid rapid application development (RAD).

With Doctrine also comes DQL, a powerful language for querying your object models,  which is similar to SQL.

Use of Doctrine abstracts away the database concepts of tables and columns, rather you think in terms of objects, entities, properties and relationships. While this is very useful, it is very important for the developer to have an understanding of the underlying SQL that is generated from using the entity manager/DQL and querying your objects/entities.

Without an understanding of the code that Doctrine generates, it is relatively easy to build an inefficient and slow application, here are a few pitfalls that I have found are easy to fall into, and some tips that may be useful for people starting with Doctrine, or if you are trying to get a little more performance out of an existing application.

For the rest of this post I will use the cookie cutter example of a Blog website with article, user and comment object models (entities). In terms of object mapping we will assume all mapping is specified with the default (lazy) fetch method, and MySQL as our DB.

1. Always write a DQL statement for querying your object models

Doctrine repositories provide some ready made methods for fetching your objects such as “->findAll()” and “->findBy()”. These provide some convenience and brevity when initially developing your application but use of these functions is less flexible when further developing your application and can lead to some of the pitfalls below.

By writing the DQL yourself, you will expand your understanding of Doctrine, you have more control of the data you are trying to query and people reading your code will have a better understanding of what you are trying to do (and will find it easier to update and extend your code).

2. Beware of lazy loading when querying entities with associations

If you do not specify an ‘eager’ fetch in your object mapping, or do not explicitly fetch your relationships in your DQL statements (or if you query your objects using the Doctrine methods mentioned in point 1) Doctrine will not fetch those associations in the SQL it generates. This is helpful as you do not want to be loading resources you do not need, however when you call a related object, Doctrine needs a method of fetching these objects and it does this by lazy loading through proxies.

For example if you have an article entity, with associated comments and you want to display a list of all your articles with number of comments on the front page of your blog, you may do something like this (this code is purely for demonstration).

$articles = $article_repository->findAll();

foreach($articles as $article)
{
    echo $article->getTitle();
    echo count($article->getComments());
}

Using this code, Doctrine will initially generate a query for all the rows in the article table. As we have not ‘fetched’ the comment association, Doctrine will lazy load in the comment object for each article via an additional SQL statement. For a table containing 10 rows, this will result in 11 database queries.

//$em is the entity manager
$qb = $em->createQueryBuilder();

$qb->select('Article', 'Comment')
    ->from('Entity\Article', 'Article')
    ->leftJoin('Article.comment', 'Comment');

$query = $qb->getQuery();

$result = $query->getResult();

return $result;

Instead, by using DQL and specifying our relationships, we can use the above code to fetch the same data with 1 query vs the  11 (unnecessary) database queries generated previously. This problem grows with each additional row in a given database.

3. Use array hydration for read only actions

The Doctrine documentation recommends the use of array hydration for read only actions, this is in part due to the extra overhead (increased memory needed from loading proxies and the like) associated with hydrating objects.

If you are just displaying lists of items, or lists of entity properties for a single item (for example a product page, a list of recent blog articles, or indeed most front end operations!) you can use:

$query->getResult(Query::HYDRATE_ARRAY);

This approach can also prevent any accidental lazy-loading problems that may arise as discussed previously (due to the lack of proxies!)

4. By default Doctrine will fetch all of the properties for a given entity

This doesn’t exactly fall under a best practice, indeed making any changes here too early in the development cycle would fall under premature optimisation. Nonetheless consider the following:

$qb->select('Article')
->from('Entity\Article');

It is somewhat wasteful in terms of resources to fetch data from your database that you aren’t going to use. The above code snippet would fetch all the properties for the article entity.

Rather than selecting the whole object, in DQL you can specify specific properties to return in your select statement:

$qb->select('Article.title')
->from('Entity\Article');

However this will always return a flat array, regardless of relationships between your entities. Instead you can select and hydrate partial objects in your DQL, which will give you an object or a nested array representing your object graph (depending on the hydration selected)

$query = $em->createQuery("SELECT partial Article.{title} Entity\Article Article");

As stated in the Doctrine documents it is important to note here that this optimisation can lead to more fragile code, it may not always be clear (especially if working as part of a team, and working code written by others) that object properties have not been fetched.

5. Use prepared statements

Using prepared statements helps to prevent SQL injection attacks that have proven problematic for developers and businesses alike – Sony notably exposed a lot of user data in Summer 2011. See below for a quick example of how to use prepared statements in Doctrine.

$qb = $em->createQueryBuilder();

$qb->select('Article', 'Comment')
    ->from('Entity\Article', 'Article')
    ->leftJoin('Article.comment', 'Comment')
    ->where($qb->expr()->eq('Article.title', ':filter_title')
    ->setParameter('filter_title', $some_user_input);

$query = $qb->getQuery();

$result = $query->getResult();

return $result;

The Doctrine documentation provides a more in depth explanation for achieving this.

6. Be aware of what Doctrine is up to

If you are using Symfony 2, you can use the in-built profiler for monitoring the number of queries generated by doctrine. If you are using Zend Framework you can refer to my previous blog post covering some methods for profiling doctrine 1 or 2.

 

I hope these tips prove helpful if you are just getting started with Doctrine, or if you have been using it for a little while. If you have any tips of your own let us know on twitter @uv_d or leave a comment

Come to our first London Sencha Touch User Group Meetup on Tues 24th Jan 2012

We’ve got a great venue sorted and finalised a date of Tuesday, January 24, 2012, 6:30 PM to come and chat, share, listen and learn about all things Sencha Touch. If you are interested in cross platform mobile development (native and web) built in web technologies such as HTML5 and JavaScript then please come and join us.

Our user group can be joined here: http://www.meetup.com/London-Sencha-Touch-User-Group

We’ve been lucky enough to have Forward host the event in their amphitheatre in the heart of Camden. Details of how to get there are below:

Forward Technology
Floor 2, Centro 3, 19 Mandela Street, London, NW1 0DU, United Kingdom
http://forwardtechnology.co.uk/venue

Transport Links:

  • Underground: Camden Town, Mornington Crescent (Both Northern Line)
  • Train: Euston, St Pancras International, Camden Road
  • Bus: 274, 46

Being our first event we will be starting off soft with overviews into Sencha Touch and mobile development with an aim of getting a feel from the community as how we want to structure the events and what we all want to learn and share with each other. With that in mind we are on the look out for those of you who want to give a talk at this or future events. They can be anything from 5min lightening talks up to 30min in-depth slots: show us something you’ve worked on or something neat that we’d find useful. Please do get in touch if you want to contribute (it means you wont have to listen to us too much!)

We’re really looking forward to meeting the rest of the Sencha community in London and learning more about mobile development.

UPDATE…. WE HAVE AN AGENDA:

We have 3 sessions planned for this event each lasting 20-30 minutes with an open floor Q&A session following each. We will start the group with a beer and a slice of pizza and move onto the 3 main sessions detailed below:

An Introduction to Sencha Touch

Patrick Hamann is a Front-end developer living and working in London with a keen passion for creating great mobile experiences using HTML5 frameworks. His talk will be a taster session introducing you to Sencha Touch giving some insight into why you might consider it as a solution.

  • What is Sencha Touch?
  • A walk-through of the Sencha Touch structure
  • Capabilities and UI features
  • Real-world examples of it out in the wild

Kent Mobile: Building a mobile “something” for the University of Kent

Matt Spence is from the IS web team at Kent University and will be providing some incites into their experience with Sencha Touch.

  • The pressure to deliver something on a mobile platform
  • How we arrived at Sencha
  • What we’ve done
  • Where we’re going

Building cross platform apps using Sencha Touch

Rob Squires is a Lead Developer with UVd with a penchant for utilising well established programming methodologies with new technologies. He is a Sencha fan and keen squash player.

His talk will focus on some techniques and considerations involved in building cross platform apps using Sencha Touch

  • A quick look at common cross platform challenges
  • Some techniques that could be useful for a Sencha project requiring cross platform deployment

Google to penalise websites that are not mobile friendly?

GOMO

Having spoken to our SEO specialist last night I was intrigued enough to do a bit of digging around Google’s position on ranking the usability of websites when viewed from different devices and how this fits in with their ranking algorithms. From an SEO perspective, our guy claimed that very soon Google will start penalising websites which are detrimental to mobile experiences.

First port of call for me is Google’s very own initiative GOMO, a pretty straightforward but useful site which lays out the business case for making your website mobile friendly, describes some of the basic principles of how to go about producing mobile friendly experiences and links to various resources for further reading/research. As a side note, when you get a chance, take a look at their site on your mobile devise as they have gone for a separate mobile site as opposed to a responsive solution and you can tell by the user experience and performance: it’s a nice example of an effective mobile website (yes I know that sounds like stating the bleed’in obvious given the context).

The ‘Gomo-Meter’ is a useful tool for testing how mobile friendly a given website is. It provides a scoring mechanism, summary report and visuals as well as a rather useful detailed pdf report providing guidance on improving the mobile experience of the site you are testing. If you are digital agency such as us trying to sell your mobile website design/development services there is nothing better than a report generated by Google, demonstrating how (badly) a potential client’s website performs on a mobile device and outlining how best to remedy the problem/s. To give you an idea I ran the BBC website through the metre (see below):

gomo-bbc

At first, when our SEO guy mentioned Google might start penalising websites with poor mobile experiences we were unsure how they would go about it. To quote Pete “How do you write an algorithm for that?” but Patrick’s response “If anyone can write an algorithm for that it’s Google” just about hit the nail on the head. This is bread and butter for Google.

Having thought about this some more, there are a number of rudimentary tests which could be easily performed, testing the 2 fundamental principles of good mobile experiences:

  • How fast does it load?
  • Accessibility (is the content fluid and viewable on a mobile without scrolling all over the place and are interactive elements given enough space?)

As we know, the former is already performed by Google and the latter is not so difficult to envisage. Other good design practices for mobile web experiences include search, contact and location information being easily accessible from the first page. This is due to the nature of mobile users who want to access information quickly (through the search) and are often looking for contact or location information in the first instance. An automated test for these elements could be achieved if Semantic Web principles (utilising the W3C’s Resource Description Framework or RDF) are adhered to and then tested for by Google.

I’m pretty sure Google are far cleverer than I so I’ll leave it to them to discuss my suggestions further and come up with a beautiful algorithm :-)

For those who are still wondering why Google might introduce ‘mobile friendliness’ to their rankings, the expanding use of mobile devices is becoming something they cannot ignore: growth in smart phone usage, sales via smartphones, engagement via smartphones and growth in web browsing on smartphones is at an exponential rate and as a consequence this is changing the way we all experience the web:

  • Smartphones sales surpassed the combined global market of desktops, laptops and notebooks in 2010 http://bit.ly/gCkOt4
  • Traffic to mobile websites in 2010 grew 600% after tripling between 2009 and 2010 http://bit.ly/cYWwJj
  • Google’s mobile searches grew 130% in the third quarter of 2010 http://tcrn.ch/haMlZm

So to conclude, it looks like our SEO guy might be right, Google appears to be moving toward some sort of introduction of ‘mobile friendliness’ into their rankings. Good news for those of us who have been banging on about sites needing to be accessible across all devices.

Full Frontal 2011

Earlier this month I attended Full Frontal Javascript 2011 conference hosted by Remy Sharp in lovely Brighton. I’ve wanted to attend since it started three years ago but have always had something in the way. So I jumped on a train at stupid o’clock on a very cold and misty morning and managed to finish off ‘Mobile First’ on the commute before grabbing a well deserved coffee with Tom Parker at Coffee@33.

The conference was held in the beautiful ‘Duke of Yorks’ independent cinema in Preston Circus, meaning the comfy sofa seats were a serious upgrade from the normal plastic seats I’m used to at conferences. Perfect to settle into for a day of insightful talks after my early rise. I won’t discuss all of the days content as we’d be here for weeks, but here were my highlights.

CoffeeScript Design Decisions – Jeremy Ashkenas

I was extremely happy to see Jeremy on the bill for Full Frontal, as we’re big fans of Backbone.js in the office and try and squeeze it into every project. That said he was actually on the bill to speak about Coffeescript, a new approach of writing js in a minimal fashion that at the same time tries to smooth out some of the ‘gaps’ in the language. I won’t go into the details of Coffeescript as you can learn more here, but Jeremy explained the core concepts very well; you would hope so from the creator;). The main points I took home were ‘It’s ok to cheat!’ why should we have to re-wrtie the book every time we start a project, but at the same time using Coffeescript we can extend/bend js language to our own.

“HTML5 is about taking js seriously!”

Excessive Enhancement – Phil Hawksworth

Phil’s talk was on a subject very close to my heart about ‘Excessive enhancement’. With the boom of Javascript over the last couple of years, especially surrounding UI development and DOM manipulation, he raised some very important questions. Are we over doing it with our ‘Browser sizzle’? Is it ok to load in 10mb of images on page load for some fancy effects or should be loading them in lazily? Whoever thought the hashbang /#! was a good idea? That last point was probably the most important, are we going to look back on this era of the web as the years of lost content. Start using the History API and .pushState() today!

Scalable Javascript Application Architecture – Nicholas Zakas

The talk I was looking forward to the most, if you’ve ever done any research into js design patterns or application architecture you would have found Nicholas’s name; he didn’t let us down. The talk was full of clear and concise definitions of architecture principles such as the module and mediator patterns and went on to describe how to structure your applications for re-use , extensibility and scalability. It really drilled home to me the importance of planning ahead in your application design to try to loosely couple as many components as possible.

“A scalable js architect allows you to replace any block in a Jenga tower without fear of it toppling over”

If you haven’t already done so, I strongly advise checking out his slides here.

Beyond the planet of geeks – Brendan Dawes

A very controversial move to have a designer most famous for his ‘Flash’ work to talk at a JS conference… but I bet everyone was happy he did! Extremely insightful for me, forcing us to take a step back and remember that our work can still be fun.

“If you don’t go into the woods, nothing will ever happen in your life.”

Drawing from his obsession of collecting weird objects such as pencils, to his work at Magnectic North, Brendan showed us that we should ‘obsess about our tools’. He also expressed the importance of continuing to experiment and explore new technologies and interfaces, canvas, svg e.t.c as they are here to be used today. His talk was summed up by my favorite quote of the day.

“When you get good at something try something different”

Although agnostic of languages or platforms, Brendan hinted towards the end of the Flash era and even stated that although it will always have its uses to become ubiqutus we may ‘need to leave some things behind’.

You gotta do what you gotta do – Marcin Wichary

What can I say, this guy has the best job in the world. For 20% of his time Marcin is one of the interface engineers for the ‘Google Doodles’. Be it Pac-Man or dancing lady, he has worked on some very cool projects. In this talk he showed us how they have used some very clever techniques to overcome the issues you can have trying to serve a project to 6 billion people. For example crushinator which cuts up animations into individual frame sprites that get overlaid on each other or using the devices accelerometer to control submarines. By far the funniest and most interesting talk I have seen this year!

Overall the day was a great success for me. I was very glad that the subjects of the talks were well rounded having something for everything and not just about how we should be caching our for-loop vars. All were educating and insightful, which leads me to think that the lack of video recordings is a shame as this knowledge may be lost forever (but I know that Remy is working on this ☺). Although, at the very reasonable price of the conference I don’t blame the man, in this day an age of conferences costing towards £1000 Full Frontal is an absolute bargain and extremely good value for money. Finished off with good discussions with friends and a nice drink by the seaside. What more could you want from a conf? I’ll definitely be back next year!

London Node.js User Group

Last night we attended the inaugural London Node User Group or to those in the know l-nug #lnug. We have been experimenting with node.js internally here all year and are extremely excited by the prospects it may hold for our clients and us in the future, aside from the fact we love all things javascript and who wouldn’t want to write asynchronous code….

The event was hosted and sponsored by the fine chaps at Forward in their rather swanky Camden offices and kicked off with a lovely round of free drinks and pizza (courtesy of Forward), some great informal networking and discussions surrounding the likes of the new Kindle Silk browser and Facebook’s plans to take over the world. A good warm up to get the brains ticking for the night’s 3 main talks:

Forward’s own Andy Kent started the night with: “Real time data analysis over unbounded streams” a look into the libraries he has been producing internally at Forward for real-time keyword data analysis specifically his Creek streaming aggregator used in production to track popular words and urls across different data streams. We were particularly impressed to see it being benchmarked in production environments clocking 500 hits a second without even flinching.

Garren Smith gave a very insightful talk “These are the ORM’s you are looking for” discussing a few options you have for ORM’s in node to create abstraction layers between your code and your lovely NoSQL db’s for object relational mapping bliss (and we are big fan’s of ORMs). Specifically LazyBoy which he wrote for couch (our personal favorite NoSQL) and we have used for personal projects. Bringing support for defaults, CRUD, relationships (hasmany e.t.c) and couch view goodness.

Rob Tweed finished the night with a rather controversial (well at least at a node group) talk on the Globals database, a very reliable high performance in-process (i.e. no network layer) NoSQL database (tongue twister) that predates the NoSQL era, abstracted from Caché db. My favorite quote of the night was from Rob, when discussing getting into node.js:

If Douglas Crockford is talking about it, then it must be good!

Not for the faint hearted, Globals is a extremely low-level storage engine for which you have to write your api’s yourself, even indexing! However, this allows you to be a lot more flexible in creating your db’s. Rob’s interesting point was that after a lot of testing and benchmarking he found that when using Globals and “blocking” on high performace enterprise level projects, synchronous db calls where faster than the as aysnc possibilities node gives us. This led into a great Q&A session from the all the aync fan boys in the room.

After the event we all headed to the grand union for some post-event discussion, where I discussed the possibility of using Node in some upcoming mobile projects we have, with some great ideas coming from people for real life uses for sockets and node in mobile development, so watch this space.

Overall the event was a great start to what – we hope – will be long running user group, a great community of people all pushing the technology to new and exciting places. Firmly rooting the fact that server side javascript is here to stay, and is ready for production use! A massive thanks to Andrew Nesbitt and Andy Kent and Forward for being great hosts. We’re always happy to meet new friends in the london tech scene so why not follow us on twitter: UVd Patrick Hamann

I will update the post once the slides/videos for the night have been released.

UPDATE: Forwards Flickr photoset from the night.
UPDATE: Video of Andy Kent’s talk “Real time data analysis over unbounded streams”

Native App beta testing with TestFlight

TestFlight
The prototype of our latest mobile App has flown the nest with the help of the very useful iOS beta testing software TestFlight which is proving to be a great tool during our distribution, testing and UAT cycles.

Patrick discovered TestFlight during the end of our phase 1 development of a mobile betting application for one of our clients ABETA International. As we’ve mentioned before, we build mobile web applications and native mobile applications using the SenchaTouch Framework; enabling us to produce intuitive mobile user experiences (UX) and user interfaces (UI) with the expertise and technology we have gained over years designing and building websites. Not wishing to repeat myself too much (it’s all here) we then package this up using PhoneGap for delivery to iPhone, iPad or Android devices.

One of the hurdles once the App is ready for client testing, bug testing or user acceptance testing (UAT) and the subsequent rounds of incremental version releases is how to achieve this in the most efficient way possible: obviously with website and web applications it’s a matter of setting up a staging or testing environment and providing a link, following that can be several rounds of testing – bug fixing – testing (I have paraphrased this process for illustration purposes only) but with Apps it’s a bit harder as we have to be able to distribute the App to the devices that our developers, clients and testers are using and in the case of our clients they are not in our office.

TestFlight is brilliant for this; from a single entry point you can distribute to predefined groups, set up new users within a group and create custom distribution lists to send new builds over the ‘air’. In simple terms, we can release a new iteration of an App and it gets distributed to the group who are alerted to the new version. Users can send feedback directly through the app (with in-app questions using their new SDK) or by replying directly to TestFlight automated emails, and this feedback is distributed to the developers assigned.

Its early days and we have only scratched the surface of what TestFlight can do but I thought I’d give my first impressions as it might be of use to others.

London JS: node.js & express.js

Last night we attended our 3rd London JS meetup, held at the offices of the event sponsor Poke, in Shoreditch.

Hungry from another busy start to the week, we were once again pleasantly surprised by Poke’s generosity who had provided 15 (we counted) Papa John’s pizzas and enough Peroni to put a Pizza Express to shame. There were 3 talks on the agenda + we had been particularly looking forward to hearing what the speakers had to say about Node.js.

Paul Kinlan started proceedings discussing and demoing LeviRoutes, a javascript routing framework he had built for Google.io. Using the HTML 5 History API, this looks like a bloomin’ useful bit of kit when you’re developing single page apps.

Alex Young then gave us a great account of implementing Node.js + Express in the real world, providing some particularly useful + comical tips on how/when to persuade a client that node is the way forward.

Michael Smith ended the evening with his introduction to Nodejs, discussing the wider applications (other than as an HTTP server) that node is suited to and even fitting in some live coding before his battery run out!

Another great event from London JS, thanks guys…looking forward to the next one!

Pete Has Arrived!


Our latest and greatest new arrival to date, Peter Mitchell, ‘Mitch’ or as he is now known ‘Maverick’, hot off an MSc in Cancer Immunology and Biotechnology is now utilising his analytical and practical skills within the Web Development arena! UVd welcome Pete to the fold with open arms and look forward to sharing many cups of tea and cake with our newest Web Developer extraordinaire.

Responsive web design and small screen optimisation

responsive web design

The way people are using and accessing websites is changing. This is due to users having more diverse browsing experiences on a multitude of devices, including desktop browsers, smartphones, tablets and more. This creates challenges for web producers regarding how we should design for different screen sizes, resolutions and types of interaction (e.g. touch). More than that, it calls into question what it really means to design for the web today.

With new devices available, the one-size-fits-all approach to web design that we’ve stuck with for so long is no longer relevant. It’s now essential that the designs that we create are responsive to the different ways that users access our content. This document is intended to outline a process called ‘responsive web design and enhancement’ that can be used to optimise your website’s content and adapt to different screen sizes and devices. Download the document here:

Responsive web design and small screen optimisation

Implementing Barclaycard’s ePDQ CPI in the Zend Framework

Barclaycard's ePDQ + ZendWe are working on an e-commerce project at the moment (built in Zend), which at it’s commercial core, involves selling digital products to consumers. Our client is using Barclaycard’s ePDQ Cardholder Payment Interface (CPI) to take secure payments from their customers.

ePDQ is well documented by Barclaycard and we had no trouble designing the transaction process for our client. However, when it came to the actual Zend development I was surprised not to be able to locate any existing Zend or even PHP classes online, over and above the simple CURL examples Barclaycard provide in their documentation. Subsequently, when designing the technical ePDQ integration I decided to put my reusability hat on and looked to write a set of Zend assets which we could add to our ever growing UVd Zend library.

The following article outlines how I developed these assets in the context of the ePDQ process. I will make the code available in uvd Labs as well.

User Flow

The diagram below illustrates the user flow when interacting with ePDQ from a generic application.

ePDQ User Flow

  1. User is presented with a checkout screen in the application, which along with an order summary includes a ‘Continue to payment’ button. When pressed, the user is redirected to the first of two ePDQ CPI screens (CPI 1) to securely input their billing information
  2. User inputs their details and presses ‘Submit’
  3. User sees result of validation on CPI 2 and is presented with a ‘Continue’ button
  4. When pressed, the user is redirected back to the application where they continue with the sales process accordingly

Application Flow

The application logic required to implement the user flow is prescribed by the ePDQ process itself.

ePDQ Application Flow

  1. To access CPI 1, an HTTP POST request must be made which contains a strict set of variables. These are both supplier specific (e.g. the application’s merchant ID) and transaction specific (i.e. order number or total value). These must be sent to the CPI encrypted, so before the checkout screen is outputted to the user, a server side call must be made to ePDQ to encrypt the details. The configuration of the CPI, (including client Logo, whether delivery address is required, currency, pre-populated fields etc) is all based on the data supplied in this POST request; the most straight forward way to implement this being an HTML form.
  2. Once the user enters their details and presses submit, two things happen. The CPI performs its verification on the transaction itself. The CPI performs a callback to the application via a POST request to a specific script. This URL must be the same for every transaction (it can’t contain OID for example) and must be protected behind the HTTP Basic authentication mechanism. It also must NOT require a port number to be specified (as I found out the hard way). The callback body contains the results of the user’s credit card verification and allows the application to perform the necessary processing such as write to a log file or database. The user will not be presented with CPI 2 until ePDQ has received a response from the application, so it is preferable to perform a minimum amount of processing here.
  3. Once the user presses continue on CPI 2, they will be redirected to a URL on the application (this URL can be transaction specific). As far as ePDQ is concerned the transaction is now complete, so the application can handle the user’s return based on the results of the callback function.

Implementing ePDQ in Zend

Based on the application and user flows of the ePDQ process, what areas lend themselves to generating reusable assets? Its clear that anything application specific such as models (i.e. sales orders or products), views (such as the checkout) should be left to the specific application to implement. Similarly, once a user is directed back to the application, any ePDQ involvement is now over so there wouldn’t be much in terms of reusable code at (3) above. However, the initial encryption request and the callback are specifically controlled by the ePDQ process, making them good candidates.

So, in terms of building reusable assets in a Zend application, what options do you have?

  • Controllers
  • Modules
  • Library Classes
  • Services
  • Action Helpers
  • View Helpers

From my experience of building assets in Zend you want something that:

  • is fairly self contained (whereas controllers perhaps are not so good, modules are self contained)
  • suits all types of implementations (our Services provide our Doctrine integration so wouldn’t suit all applications)
  • are easy to make application agnostic (plugins and classes are)
  • can be developed with caching in mind

Having digested the technical documentation from Barclaycard and after thinking long and hard about Zend, I decided the best approach would be to develop:

  1. A library class – UVd_Commerce_Epdq_Service (Epdq_Service)
  2. A plugin – UVd_Commerce_Epdq_Plugin (Epdq_Plugin)

Zend Application Integration

The following diagram outlines how these assets integrate into a Zend implementation of the ePDQ process.
ePDQ Zend Integration

1. Generating the checkout view

In order to render the checkout view, the checkout controller instantiates Epdq_Service. This collects application specific variables (merchant Id) from an epdq .ini file and all transaction specific variables are passed by the controller. Epdq_Service makes the server side HTTP request (I used Zend_Http_Request, using CURL). Once this is received the Checkout controller can call htmlify() on the object and an html form will be generated.

2. Processing the callback

ePDQ needs the URL of the callback function (which you configure in the ePDQ admin interface). This URL is stored in the epdq.ini as a collection of module, controller and action names, however the actual controller does not need to exist in your application. Epdq_Plugin looks at the ini file and intercepts any calls made to this combination; this is checked using the dispatchLoopStartup hook. The plugin provides the HTTP authentication mechanism and then calls Epdq_Service to perform basic processing on the results, which is a simple log to a text file. Each application will want to process this result differently so the advantage of this approach is that all application specific code can be put into an actual controller with the same name.

3. User exits ePDQ

The user will then press continue and will be redirected to a URL on your application that is transaction specific. It makes sense to include the OID in here so the application knows how to continue with the user flow. I am also storing this in a session to prevent URL tampering.
I hope this has proven a useful resource for anyone using ePDQ with Zend. I will also make my final code available in uvd Labs so look out for that!

Search