Some time it is necessary to fool your PHP application to test functionality related to a “current date”.

Fooling php cli is simple using faketime:

Say you have this PHP script:

#!/usr/bin/env php
<?php
print date( 'F j. Y [H:i]' )."\n";

Rendering this script with php through faketime will give you results like this:

$ faketime 'last Friday 5 pm' ./time.php
December 9. 2011 [17:00]

The same can be achieved using the datefudge command:

$ datefudge "2007-04-01 10:23" ./time.php
April 1. 2007 [10:23]

Faking time for a webapplication

Faking time for a web application is not that simple since apache will fork a process for each request and thus create a new php processes.
In this post I will show you how to use FakeTime Preload Library to fake time system wide while running tests on a web application.

First I need to install faketimelib as described on the librarys homepage.
In short:

wget http://www.code-wizards.com/projects/libfaketime/libfaketime-0.8.1.tar.gz
tar -xvzf libfaketime-0.8.1.tar.gz
cd libfaketime-0.8.1
vim README
make
sudo make install
export LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1

For the demonstration I will use a php script like this:

<?php
printf( "The current time of the server is: %s\n", date('l F j. Y [H:i:s]') );

Running this script should yield something like:

$ php time.php
The current time of the server is: Friday December 16. 2011 [08:02:43]

Now I create a file in my home folder, faketimerc, with a new future time. I will use this file in different ways to show how I can manipulate the time.

echo "@2012-12-21 12:12:12" > faketimerc

If you now create an environment variable, FAKETIME, give it a future time, and running the same script would yield something like this:

$ php time.php
The current time of the server is: Friday December 16. 2011 [08:19:39]
$ export FAKETIME=$(cat faketimerc)
$ php time.php
The current time of the server is: Friday December 21. 2012 [12:12:12]
$ unset FAKETIME
$ php time.php
The current time of the server is: Friday December 16. 2011 [08:19:56]

As you can see, the processes you run while the environment variable is set to a future time will get a fake time. Once the variable is unset new processes will get normal time.

This can be achieved also by creating a file. “.faketimerc” in your home folder:

$ php time.php
The current time of the server is: Friday December 16. 2011 [08:23:12]
$ cp faketimerc .faketimerc
$ php time.php
The current time of the server is: Friday December 21. 2012 [12:12:12]
$ rm -f .faketimerc
$ php time.php
The current time of the server is: Friday December 16. 2011 [08:23:36]

If you want to change time for a php application that runs though apache you may want to set the fake time system wide so that the php processes spowned use the faked time. To do this you need to create a file, /etc/.faketimerc, just the same as the one I created in my home folder.

I will use w3m for this demonstration. I assume a normal ubuntu server with apache2 installed.

sudo cp time.php /var/www
sudo cp faketimerc /etc/
$ sudo /etc/init.d/apache2 restart
 * Restarting web server apache2                                                                                                                                                                                                                                                   ... waiting
$ php /var/www/time.php
The current time of the server is: Friday December 21. 2012 [12:12:12]
$ date
fr. 21. des. 12:12:12 +0100 2012
$ w3m -dump localhost/time.php
The current time of the server is: Friday December 16. 2011 [11:16:24]

As you can see, the date command and when rendering the script with php, gives me the fake time, but when rendering the script through apache I loose the fake time. This is because the environment variable LD_PRELOAD is not set for the apache process.

To fix this I need to set LD_PRELOAD for apache by editing /etc/apache/envvars. Lets test it again:

$ sudo bash -c "echo \"export LD_PRELOAD='/usr/local/lib/faketime/libfaketime.so.1'\" >> /etc/apache2/envvars"
$ sudo /etc/init.d/apache2 restart
 * Restarting web server apache2                                                                                                                                                                                                                                                   ... waiting
$ w3m -dump localhost/time.php
The current time of the server is: Friday December 21. 2012 [12:12:16]

Fake time! :)

PS! If you also want your PostgreSQL server to use fake time:

$ sudo bash -c "echo \"LD_PRELOAD='/usr/local/lib/faketime/libfaketime.so.1'\" >> /etc/postgresql/8.4/main/environment"
$ sudo /etc/init.d/postgresql-8.4 restart

When you need to see if any of the chars in $chars is in another string.. Whats the simplest way to search for them?
Hopefully none of the libraries have such functionality, so you need to go “a bit lower”.
The answer is, ofcourse, trivial:

$chars = "xy";
$string = "the quick brown fox jumps over the lazy dog";

$found = false;
for($l = 0; $l < strlen($chars); $l++) {
        if (strpos($string, $chars[$l]) !== false) {
                $found = true;
                break;
        }
}
if ($found) {
        /* Do stuff */
}

But hang on. This feels a bit weird. Surely PHP must have a better way of doing this?
Browsing through the string section in the PHP manual you’ll notice PHP has bucketloads of native string functions. If you have a background from other languages, you could even just try and see if PHP has a function of the same name (which quite often it does) that solves the problem.

And sure enough, it does: strpbrk!

$chars = "xy";
$string = "the quick brown fox jumps over the lazy dog";
if (strpbrk($string, $chars)) {
        /* do stuff */
}

Just give the “problem” a second thought before going crazy with your coding, and keep in mind you aren’t just working with Symfony, Drupal, SugarCRM, WordPress, … Your good old pal, PHP, is there too.

Which resolution web application should be optimized to, is a question with different answer mainly depended on time when asked. The average screen size and resolution have been growing as a result of technology evolution and falling prices of electronic equipment.
Resolution usage, Source: http://www.w3counter.com/
Resolution usage, Source: http://www.w3counter.com/

At the same time mobile devices, like pads and cell phones, with small screens and low resolution, became capable to browse Internet in a more effective way.
Mobile browsing, Source: http://gs.statcounter.com
Mobile browsing, Source: http://gs.statcounter.com

So, what to do if I have in my requirements support for IPhone 3GS 3,5” 320×480 and PC screen with high resolution 1920×1080. Somehow I must optimize my application to these two resolutions.

One of the common solutions is to split the application on view level by implementing two versions of templates. One optimized for high and the other for low resolution devices. It is going to work, but is that really a good solution from design point of view. The main disadvantage is that the application is still not supporting all possible resolutions, is just optimized to high and low one. And of course another issue is maintainability and future compatibility.

What if instead of optimizing application to a specific resolution, I could support all of them. It is actually not a new idea. It has been ages since I could use size=”100%” attribute in some html tags. By doing this html element is always scaled to the maximum available size. It gives some flexibility. However scaling has limitations, sooner or later I will reach a stress point where scaling is not effective anymore and I would need to change layout by relocation some elements of interface.

So, to optimize web application to any resolution I would need to:

  • scale html objects
  • dynamically change layout
  • scale images

Generally speaking, I need an ability to alter my application, in order to continually reflect the environmental conditions.

This is what “Responsive Web Design” stands for.

In practice responsive web design is an intelligent use of flexible grids, layouts, images and CSS media queries.

Media Queries

With media queries I’m able to resolve the first two first problems, I can scale html elements and change layout.

Since CSS 2.1 there is a possibility to define custom style sheets for different media types.

@media print {
/* style sheet for print goes here */
}

@media screen {
/* style sheet for screen goes here */
}

CSS 3 offers an extension called media query, which allows to specify conditions when the specified style sheet will affect user interface.

@media screen and (max-width: 640px) {
/* Window size < 640px */
}

@media screen and (max-width: 800px) and (min-width: 640px) {
/* Window size between 640px and 800px */
}

@media screen and (max-width: 1024px) and (min-width: 800px), (max-width: 640px){
/* Window size between 1024px and 800px or less than 640px */
}

Here is an example of valid media query definitions:

<link rel="stylesheet" type="text/css" media="screen and (max-width: 640px)" href="shetland.css" />

@media screen and (max-width: 640px) {
/* Window size < 640px */
}

@import url("style.css") screen and (max-width: 640px);

If a web browser does not support media queries css is loaded always without any conditions, this is unwanted behavior. If you want to prevent loading css with media queries on not supported web browsers you can add word “only” before media type:

/* add word «only» to be ignored on web browsers with out support */
@media only screen and (max-width: 640px) {
/* Window size < 640px */
}

There is quite many criterias available in CSS3, however the two first on the below list are the most usable.

  • max-width / min-width
  • max-device-width / min-device-width
  • orientation (portrait/landscape)
  • device-aspect-ratio
  • min-resolution / max-resolution
  • monochrome
  • Min-color-index

See http://www.w3.org/TR/css3-mediaqueries for more

CSS Media queries are supported by the following web browsers:

  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera 9.5+
  • Opera Mini
  • Android Browser
  • Opera Mobile
  • IE9+

CSS media queries are quite useful if the goal is to affecting mobile devices, it is supported by most of the web browsers used on mobile devices.
But if the goal is to support older web browsers Java Script comes with help.

Here is an example of loadCss() and removeCss() methods that can be used to dynamically load and remove css files.


/**
* Load CSS file
*/
function loadCss(filename){
var links = document.getElementsByTagName("link");
for (var i=0; i < links.length; i++) {
if(links[i].getAttribute("href") == filename) return;
}
var fr=document.createElement("link")
fr.setAttribute("rel", "stylesheet")
fr.setAttribute("type", "text/css")
fr.setAttribute("id", filename)
fr.setAttribute("href", filename)
document.getElementsByTagName("head")[0].appendChild(fr)
}

/**
* Remove CSS file
*/
function removeCss(filename) {
var links = document.getElementsByTagName("link");
var parent = document.getElementsByTagName("head")[0];
for (var i=0; i < links.length; i++) {
if(links[i].getAttribute("href") == filename) {
parent.removeChild(links[i]);
}
}
}

 

Adding below code to onResize event will be equal to: @import url(“mini.css”) screen and (max-width: 400px);

/* Activate mini.css file if window size is less than 400px */
if(windowWidth<400) {
loadCss('mini.css');
} else {
removeCss('mini.css');
}

The above example should in theory by compatible with old web browsers (including IE6) .

Images

The last of my needs is to scale images, here are few ways how I can do it.

Fluid images

When user opens my application on a mobile device with small screen and low resolution or changes web browser window size, it might happen that my images will reach a stress point where they will consume more space that the window is able to offer. To avoid this problem I need to scale them proportionally.

Fortunately there is a CSS property called max-width, if I set to 100% in theory I get all I need. My images will by default be displayed in their original size and will be proportionally scaled when needed.

But in practice this solution is affected by few problems, the main is that I will need to load oversized images in low resolution which can be a problem for small mobile devices. The other problem is a poor quality of scaled images on IE.

Hiding images

Another possibility is to have alternative versions of an image, depending on the environment images can be visible or hidden, just like on the example below:

.small-image {
display:none;
}

@media only screen and (max-width: 600px) {
.default-image { display:none; }
.small-image { display:inline; }
}

<img class="default-image" src="img1.jpg">
<img class="small-image" src="img2.jpg">

 

It works quite well, if windows size is below 600px (this is the stress point) small-image gets attribute display:inline; and default-image gets display:none;
Nice solution, compatible with all common web browsers, however IE always loads both images even if one of them will never be showed and it is not quite clean code.

“Content” attribute

It is possible to show images with combination of content property and url value, see example below:
@media screen and (max-width: 600px) {
.image1:before {
content:url(img2.jpg);
}
}
@media screen and (min-width: 600px){
.image1:before {
content:url(img1.jpg);
}
}
<span class="image1" />


But still, this code isn’t clean and is not compatible with some common web browsers.

Java Script way

JS come here with help as well.

One of the possibilities is to set a cookie with screen size information.
document.cookie = "screenWidth=" + screen.width;
and then serve all images through media content, which will send the right image version depending on screenWidth value:
<img src="media/?test.jpg">

CSS 3 way

In the future I’m expecting below code to be supported in all CSS3 compatible web browsers, for now only Opera supports this syntax partially.

<img src="test.jpg"
img-400px="test-400px.jpg"
>
@media (min-device-width:400px) {
img[img-400px] {
content: url(attr(img-400px));
}
}

With the recent massive flood of frameworks, libraries and toolkits on the market these days it is easy to forget that underneath it all is the good old, plain and simple, PHP with all its kinks, quirks, and huuge set of builtin functionality.

PHP has vast amount of extensions which solve all sort of problems. And if PHP doesn’t have it built-in, we have an impressive amount of additional extensions both on pecl and now recently more and more on github.
There is a high chance that someone else has been in your shoes already and solved the problem, so it is worth looking around over the horizon and see if the problem has been solved already.

For some reason the current practice seems to be the “RoR” idiocy where “RoR developers” barely even know that there is this Ruby some miles down the stack. PHP has hit this “stepping stone” already with WordPress, Drupal and even Symfony and that is a weird and scary thought. Remembering “where you came from” is an important fact to remember, even for those who specialize in specific products. Looking at how other projects work, comparing notes, work ethics, features and functionality is also very important. Getting different perspective and knowledge is how we can improve our solutions and work more efficiently. If your specific product doesn’t have native support for something, why not look at a different framework/library/cms/toolkit/.. even PHP extensions?

As June mentioned earlier, going ‘back home’ and checkout the PHP manual pages is generally a good idea. Things change, manual pages are updated, improved, added, and you have different perspective, other problems to solve and so on. Even though you believe you know all the basics, you still need to practice them, and that includes browsing the manual from time to time, again and again – no matter which project it is.

So what is the best way to stay in touch? Kept up2date with new ways and offerings? New solutions to the same problem? Get involved!

By far the best way is to get involved with the project you are using. Even just silently idling on the mailinglists and read the subjects. Subscribing to the commit lists is a fantastic way to see precisly what is going on and see which direction the project is taking. Who knows, after a while you may spot something the others didn’t. Get an idea for a killer feature. Shed a light on different perspective the others didn’t think of. After a while hanging on the lists you’ll get a feeling for how the project works, and hopefully start chiming in. Give your 2cents, and who knows – even cook up a patch or two.

Introduction

Whilst everyone is buzzing and creating fancy new Symfony2/Doctrine 2 applications, and perhaps even a shift to new frameworks/no frameworks, a great deal of us are still maintaining legacy apps and will be for some time to come. As these apps grow, we occasionally need to look back and scream at our old code and wonder why we didn’t make it more scalable or use neat optimisation tricks back when it was first conceived. The fact is, many of these “tricks” are not necessary at the time for a virgin app, and we need to develop code that is relevant to the task at hand.

That said, being aware of some of the case studies I will present to you now may help you to optimise old code, but may also allow you to think twice when you are working with new code – as the things I will describe do not take too much time to implement first time round.

Case study: Working with large resultsets and array_merge

In my sample application, the database contained many different types of organisation stored in different tables, and due to the structure of the data and the criteria for each organisation, there was no easy way to retrieve several organisations at once using pure SQL and joins (well, no convenient way). The solution is relatively simple, one query per organisation then combine the results, in this case as we go along:

$membershipClasses = array("Entity1", "Entity2", "Entity3", "Entity4", "Entity5");
    $results = array();
    foreach ($membershipClasses as $joinedTable)
    {
      $query = $this->createQuery()->from("TablePrefix".$joinedTable." t");
      // Lots of differing criteria based on which class we were dealing with
      ...

      $results = array_merge($query->execute(array(), $hydration), $results);
    }

This logic was used to generate a report with approximately 50,000 rows, used 1.2GB of internal memory and took around 20 minutes to complete – often failing or bringing the system to a halt.

One optimisation used in this case (many more are surely possible but lets focus on one) involves the last line – using PHP’s array_merge function. Simply switching this out to use a simple array traversal brought the execution time down to under 2 minutes, however there was no change in memory usage.


$theseResults = $query->execute(array(), $hydration);
foreach ($theseResults as $aResult)
{
  $results[] = $aResult;
}

Why is this so much faster? And why can’t we use += instead?

 

The “problem” with array_merge, is that even though it discards numeric keys, it still has to *check* them all first, which is a lot of overhead on 50,000 rows. We can’t use += in this case either, because that would respect the numeric keys which would start from 0 each time, and therefore the results would not “stack” as intended, unless we tell Doctrine to index the results with some unique key.

Why it takes *so* much longer is a bit of a mystery to me. I’ve looked at the c code behind it (ext/standard/array.c) and it’s, well quite frankly voodoo.

Case study: Limiting results

Something that was “fixed” (read: removed) in Doctrine 2 was the ability to limit results returned from queries, at least the “magic” part of it. The problem with limiting hydrated results is that you need to know exactly how many rows each sub-tree will contain before you can limit the query as a whole. Imagine a person with many addresses, and you want an array limited to 5 people – you can’t list add “LIMIT 5″ to the end of the query, because when this is hydrated you will most likely end up with one or 2 people, the second of whom may not have all their addresses, because you’ve told your database manager to return 5 *rows*, it has no idea how these rows relate to your model.

In Doctrine 1, adding a limit clause would cause all sorts of magic to happen, the resulting query ending up as a collection of complex subqueries each with their own limit clause, the more joins you introduced, and the more levels of join, the more complicated it becomes. First level joining is not so bad, but joining several levels deep soon starts to get heavy, and your execution speed will suffer for it. Couple this with a large resultset and you will see the smoke drifting from the server room in no time.

So, what’s the solution? Well, this one is not so clear cut – you have to experiment. Sometimes, doing it the “magic” way will work just fine, and is totally acceptable, but when the query becomes “heavy” you have a few options:

Work out your subset first

This is the default Doctrine 2 approach, it’s quite simple – you use one query to get all the ids of the subset of top level elements, then pass these IDs to another query in a “WHERE IN” clause. When you look at the resulting SQL, it can be quite scary, especially if you are dealing with many results – you can easily be saying “WHERE IN (1,2,3,4…..9999999999)”. Most dbms will handle this surprisingly well, as long as you are using the primary keys, so experiment with it and it might be the way to go.


if ($limit)
{
  $subQuery = $this->createQuery("foo")
                   ->select("foo.id")
                   -> //
                   ->limit(50);
  $ids      = $subQuery->execute(array(), DOCTRINE_CORE::HYDRATE_SINGLE_SCALAR);
  $query->andWhereIn("cf.id", $ids);
}

Note the use of “single scalar hydration” – we have no need for more than this (to be really picky could go straight to PDO here but for consistency this is ok). In this case, the single scalar hydration will give us a resulting array of raw IDs, which is exactly what we need to pass to the main query.

Make your own subquery

A variation on the above is to embed the “ID sucking” query into your main query, some database engines may prefer this style, but I have not noticed any significant performance gain or loss doing this so prefer the above option as it’s cleaner in the PHP code.


$query->whereIn('SELECT id FROM my_other_table WHERE blah LIMIT 50');

In a perfect world, this is the kind of thing Doctrine could have done instead of the subquery magic, but there are so many factors to consider here that I can understand why they did not go down that route.

Stick with the magic, but simplify

It is also possible to continue using the magic, but greatly improve performance by simplifying. Remove all those second+ level joins and use separate queries to get hold of the data you need. How often have you added a chain of joins just to get one snippet of data from the last node? Scrap all the joins and make a new query later where you can pass in all the IDs from your main query and get the data you need. Now you don’t need a limit clause, because you are asking for exactly the data you need in the first place.

Start with the fastest hydration mode and work upwards

This one I can’t stress enough – an ORM such as Doctrine is there to give you the tools you need when you need them, but it is often the case that applications are built with all the overhead and magic just because it can be, or because it’s the default behaviour. Stop. Look at what data you *actually* need, and especially ask yourself if you need objects in your results. Perhaps you are retrieving all your users and listing them with their profile data, but you are hydrating them as objects because you need some custom functions you’ve written, classic examples are getAge() or getFullName() which are derived from other fields. If this is the only reason you are object hydrating, consider something like this:


class User
{
  function getAge()
  {
    return self::getAgeFromDOB($this["dob"]);
  }

  function getFullName()
  {
    return self::getFullNameFromUserArray($this);
  }

  public static function getAgeFromDOB($dob)
  {
    $dob = strtotime($dob);

    $year_diff  = date("Y") - date("Y", $dob);
    $month_diff = date("m") - date("m", $dob);
    $day_diff   = date("d") - date("d", $dob);

    if ($month_diff &lt; 0 || ($month_diff == 0 &amp;&amp; $day_diff &lt; 0))
    {
      $year_diff--;
    }
    return $year_diff;
  }

  public static function getFullNameFromUserArray($user)
  {
    return $user[&quot;first_name&quot;] . &quot; &quot; . $user[&quot;first_name&quot;];
  }
}

In this example, we’ve kept the sideways compatibility of the getFullName function with array/object hydration, so it will work whether an object is passed or an array (sanity checking needed of course). This method could be expanded to support more “raw” hydration methods also. Now in our templates, we can just use:

<li><?php echo $user["username"]; ?></li>
<li><?php echo $user["Addresses"][0]["city"]; ?></li>
<li><?php echo User::getFullNameFromUserArray($user); ?></li>
<li><?php echo User::getAgeFromDOB($user["dob"]); ?></li>
<li>...</li>

This can massively speed up your application if you have long lists or are generally dealing with lots of data, especially data than spans several levels.

Lets also take a second to consider the super fast hydration methods, if we are really struggling for resources (perhaps working with large downloadable reports) and we can live with slightly less friendly arrays of data, scalar hydration can save the day. Shifting to scalar hydration means we lose the ability to later instantly switch to object hydration due to the alternate syntax and lack of nesting, but if we are considering scalar hydration in the first place we are probably in a situation where object hydration will never be practical.

<li><?php echo $results["u_username"]; ?></li>
<li><?php echo $results["a_city"]; ?></li>
<li><?php echo User::getFullNameFromUserArray(array("first_name" => $results["u_first_name"], "last_name" => $["u_last_name"])); ?></li>
<li><?php echo User::getAgeFromDOB($results["u_dob"]); ?></li>
<li>...</li>

I could go on and on but I hope these points have given you some food for thought!

© 2011 Redpill Linpro PHP Competence Group Suffusion theme by Sayontan Sinha