Archive for the Category Tips & Tricks

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

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.

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.

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!

Accessible breadcrumbs using ARIA

Modernselling.com breadcrumb

Lately we’ve been working on a lot of content heavy websites here at UVd, all of which follow the very common hierarchical structure (or taxonomy) of the web: categorised sections, which contain articles of content that are all related to that category.

When we are faced with the problem of having to show a way of navigating this hierarchical structure within our HTML it’s very common practice within our industry to use a breadcrumb pattern of markup. The most common of which up until recently has been to use an un-ordered list element <ul> and the navigation links to be list-items within the list, example of which can be seen here:

<ul>
	<li><a href=”index.html” title=”Home”>Home</a</li>
	<li><a href=”products.html” title=”Products”>Products</a</li>
	<li><a href=“shoes.html” title=”Shoes”>Shoes</a></li>
</ul>

Chris Coyier of CSS-Tricks recently wrote an article on the issues surrounding this age old pattern titled “Exploring Markup for Breadcrumbs, and suggested some markup solutions to tackle it. As Chris stated the use of a <ul> is

“semantically wrong putting each navigation item on the same hierarchical level.”

The final solution he suggests uses the HTML5 <nav> element to wrap the items, which satisfies our semantic goodness needs denoting that everything contained within it should be treated as a navigation structure, and then uses the rel attribute and the up to indicate the hierarchy on each level:

<nav>
 <p>
  <a href="/" rel="index up up up">Main</a> >
  <a href="/products/" rel="up up">Products</a> >
  <a href="/products/dishwashers/" rel="up">Dishwashers</a> >
  <a>Second hand</a>
 </p>
</nav>

Although this solution is now semantically correct and the rel attribute allows each item’s level to become machine-readable there was something that still bugged me about it, it’s accessibility towards users using assistive devices or screen reading based browsers. The up value is still in debate by the spec editors and isn’t likely to be supported in any screen readers for a long time. After a lot of experimenting and some in-depth discussions with a fellow frontend dev friend of mine Dan Claydon and a sprinkling of ARIA I’ve come to this solution:

<nav role="navigation">
<p id="breadcrumblabel”>You are here:</p>
<ol id="breadcrumb" aria-labelledby="breadcrumblabel">
<li><a href="index.html" title="Home">Home</a></li>
		<li><a href="products.html" title="Products">Products</a></li>
		<li><a href="shoes.html">Shoes</a></li>
	</ol>
</nav>

The advantages of this pattern are:

  • The use of the WAI-ARIA aria-labelledby attribute to instruct the user agent to use the label inside the <p> element to label the content of the navigation list
  • Semantics: using the <nav> and <ol> elements to create a much cleaner structure to both machines and humans
  • Separation of structure and aesthetics. You can use the CSS2 :after pseudo attribute to place the visual > separators after the links. As I am a strong believer that they do not belong in the markup
  • You can chose to either hide the label off screen using css (which I have) or leave it if it fits your design and acts as a strong visual clue to everyuser
    Although a more accessible pattern it still brings some issues along with it. The elephant in the corner and its lack of support for HTML5 elements and CSS2-3 attributes (IE 6-8). Unfortunately the only way around this is to use some of the very clever javascript “polyfills” that are popping up all over the web at the moment. Two of our favorites here at UVd , perfect for this pattern are: Modernizr and Selectivizr
  • Modernizr allows you to use advanced feature detection on the clients user agent for progressive enchancement, and also uses a great HTML5 element polyfill which will allow us to style our <nav> element
  • Selectivizr combined with your framework of choice (jQuery in our case) allows you to use some of the more recent CSS2-3 selectors in your stylesheets and parses them for the older browsers. Thus allowing us to use the :after pseudo selector for our navigation items

I would love to hear your feedback regarding this pattern and if you have any other techniques to improve the solution, and of course would like to credit Chris and Dan who gave me the inspiration. Below is a list of some further reading around the ARIA spec and accessible forms of navigation.

Log on with LinkedIn

Log on with LinkedIn
We have just completed the re-launch of ModernSelling.com which is a re-work of the design and functionality we originally built in 2006.

The old site was a passive audience experience: traditional article driven content read by the user but the aim of the new site is to encourage discussion and user contribution; discussions are started by a number of key individuals who open out their comments for other users to contribute. User’s contributions are given equal prominence to the article itself and form part of the overall site content.

One of the key features we have implemented enables users to register and subsequently log in with their LinkedIn account: instead of the traditional registration form and then double opt-in email verification process the registration is simply a matter of the user allowing ModernSelling.com permission to access their LinkedIn account, entering in their LinkedIn email and password and Bob’s your uncle we can then authenticate against the LinkedIn user account in the backend (using the OAuth protocol and the LinkedIn API). The beauty of this is four fold:

  1. Users with a LinkedIn account don’t have to worry about managing subscriptions / profiles on 2 different sites
  2. The registration process is vastly quicker and easier for those choosing to use it
  3. We can maintain up-to-date profile information about a user as it is passed from LinkedIn each time a user logs in and don’t have to rely on users updating their profile through a traditional ‘My Account’ section
  4. Although we are not currently using all the profile information LinkedIn provides and have only scratched the surface of the many different API’s available we can choose to leverage them at any point in the future without going back to our user base and asking them to fill in more information; we are essentially piggybacking the LinkedIn system

Warning: you might not get what you want

For those wishing to utilise the LinkedIn API for their own web applications / subscriptions sites / profile building there is one word of warning: unlike the Facebook method (‘The Graph API’, part of which was previously known as ‘Facebook Connect’) the LinkedIn profile doesn’t provide you with a user’s email address. This appears to be a strategic business decision by LinkedIn but poses some hurdles for those with existing databases which use the email address as a unique identifier: for obvious reasons, if the email address is the unique identifier then it is a prerequisite to have it in order to set up a user account. Furthermore, even if your database does not require an email address, your businesses sole form of direct communication with one of your users / profiles is likely to be via email – so not much use if you don’t have it!

Personally I think this is a major ‘faux pas’. Some might say it is a security issue but actually, if an individual is already giving a third party web application permission to access their user profile it is just another (important) part of personal data they are happy for the third party to use to enhance their experience.

Our solution to this issue was to create a ‘one off’ step on the first attempt to use our log on with LinkedIn process: this ‘intermediary’ page requests the email address  prior to us creating a user account for them in our database. Secondly, for those who already have a ModernSelling.com account but decided to start using the log in with LinkedIn feature we asked them to link their existing ModerSelling.com account with their LinkedIn account by providing their existing ModernSelling login details (email address and password). Both of these actions were very easy and not required on subsequent use of our log on with LinkedIn process.

Below is a screen shot of this ‘intermediary’ page which hopefully should explain it:

Log on with LinkedIn confirm LinkedIn user page

Post Script: I’m subscribed to the LinkedIn Developers network and they have released a few useful development libraries and plugins to make life a bit easier. You can find some useful plugins here and a useful OAuth JScript library has been released here (meaning front-end developers can now leverage the LinkedIn API. Note: as it stands – on 20/04/2011 –  there are some bugs in this library which LinkedIn are working to rectify)

Diagonal line filled box with ActionScript3

diagonal-line-filled-box

Just a very quick post about a potentially useful code snippet that I recently wrote in ActionScript. I discovered, after attempting to Google my way through a small bit of development, that I couldn’t find the exact solution I was looking for.

I was attempting to find some code for making a rectangle using the AS3 graphics API which is filled with a background colour and some diagonal lines (illustrated above by the green and blue boxes). Fairly straightforward one would assume however most of the examples I found involved drawing the lines and using a mask to create the rectangular shape. Considering the overhead of using masks in Flash and the fact that within my application this box will be being rendered extremely regularly to simulate movement I decided to write a little utility using only the graphics API and some GCSE maths.

The code won’t format properly in the blog so I’ve uploaded the entire DrawingUtil.as class for download here.

Going Mobile with CSS3 Media Queries

Header

You must either live in the Outer Hebrides or have been asleep for the last year not to have heard about the HTML 5 and CSS3 buzz bouncing around the interwebs: every developer or wannabe marketing exec is trying to get in on this particular piece of the pie. Therefore, we thought we’d give you a little insight into one of our favourite CSS3 modules ‘Media queries’ and how we are using it to make websites more mobile friendly.

Firstly let’s get one thing clear, contrary to popular belief CSS3 is NOT part of HTML5, it’s a completely different spec written and managed by a completely different group of people. But, much like HTML5 it is made up of multiple modules each addressing new functionality to the CSS base spec.

Although only getting a lot of attention recently, the Media queries module has existed since 2001 (yupp 9 years old!) but due to a gradual influx of capable media devices and user agents (iPhone, Android, Safari, Chrome e.t.c) they have only recently become useful.

So what are they, and how can they help me I here you ask?! Media queries are simply logical expressions that enable you to declare style declarations specific to a media device or type. Between the various HTML and CSS specs there are eleven different media types:

"all", "aural", "braille", "embossed", "handheld", "print", "projection", "screen", "speech", "tty", "tv"

We have seen media types being used for years, for instance using “print” style sheets to change a documents layout specifically for printing. Media queries extend this functionality further allowing us to specify exact aspects or “features” of a device, thus enabling very specific style declarations based upon whether features exist on the target device or user agent. These features are:

Width, height, device-width, device-height, orientation, aspect-ratio, device-aspect-ratio, color, color-index, monochrome, resolution, scan and grid.

Therefore, a media query consists of a media type and zero or more expressions that check for the conditions of particular media features, as shown in the example syntax below.

Syntax

This specific query would apply to all screen devices with a maximum screen width of 480px, which is in fact one of the queries we are using on this blog to aid the experience on more advanced mobile devices and smart phones such as the iPhone (as 480px), but you can still see these style changes now if you reduce your browser to a width below 480px.

You can now see the amazing potential of media queries in the mobile world, we can define specific styles based on the devices resolution, colour or screen size, and as it is CSS the styles will cascade down. Therefore, you can have a set of styles for all devices, which will cascade down through all of the other queries. This allows you to deliver the same content to every device, which adapts based on the devices capabilities. This makes your website pages much more future proof as we are testing for features on the device or user-agent rather than sniffing for browser versions like we had to do in the past.

We have been getting very excited at UVd recently surrounding the massive change we are seeing in the mobile world and have been gearing our own as well as our client’s websites to be ready and take full advantage of all the new functionalities to play with. I hope this post has given you a little insight into what you can do with media queries and encourage you to go and give them a try for yourself! I have also included a list of great further reading below.

http://www.slideshare.net/maxdesign/css3-media-queries
http://www.alistapart.com/articles/responsive-web-design/
http://dev.opera.com/articles/view/the-mobile-web-optimization-guide/

Utilising the TweetMeme API

TweetMeme logoWe’ve been integrating some social media into one of the sites we work on ModernSelling and specifically working with the TweetMeme API which allows users to view the number of Tweets an article / page has received and retweet said article. From the horse’s mouth:

The TweetMeme retweet button is for website and blog publishers who want to encourage their audience to tweet their content on Twitter. The button shows a live count of the number of times your webpage or blog post has been tweeted.

There are a few points worth mentioning about this integration because it is not always as straightforward as you might think and perhaps some of this information will be of use.

Firstly, TweetMeme is quite strict so for anti-spam purposes uses a combination of the Tweet which we send to the API and a custom meta tag containing a match of the tweet:

&lt;meta name="tweetmeme-title" content="The Message of the tweet " /&gt;

Additionally, the content / message of the tweet has to be a direct subset of the HTML title tag. For instance, for the example above, “The Message of the tweet” needs to be included in <title>. It doesn’t have to be the only thing in the title tag but it does have to be present.

So if like us you are generating these things on the fly (the site in question is driven by a content management system we built) you may have to make adjustments to your system to accommodate the TweetMeme functionality and also discuss compromises with your client; for instance, in our case, the title tag now includes the original title (which was specifically written for SEO purposes) with the article headline (which we want to be the body of the tweet) appended to the end. There is no way around this; the tweet message cannot contain something that is not contained in the HTML title tag so you need to live with it or not use the TweetMeme API.

Secondly, TweetMeme uses a cache which means that if someone already tweeted your page/s before you implemented the TweetMeme functionality the tweet will already be cached against the url. In these instances, if you wish a retweet to use the a new message as opposed to the old, incorrect message (your old title tag if it was incorrect) you need to clear the TweetMeme cache on a page-by-page basis or, rather than doing a manual update for a large number of URL’s you can automate the process and use the TweetMeme ping api (http://api.tweetmeme.com/ping?url=). Just append the URL that you want to update at the end of it and loop through the list of pages on your site.

Finally, part of the site we implemented this feature on is subscription only so bare in mind that any password protected url is not going to allow the TweetMeme API to make a call back to the page to verify it – TweetMeme will not work in these circumstances.

Happy TweetMeme’ing!

Search