Easy Caching with StashPHP

Frequently with PHP you are going to need to cache things, mostly expensive SQL queries, but also data you aren’t going to want to be inserting into the database on every page hit, for instance website statistics.

With PHP we have a few options to achieve this;

  • Caching with the file system .
    • Pros:
      • Works well with the Opcode cache
      • Usually the fastest method of caching for small or medium websites
    • Cons:
      • Clearing the cache can be a lot slower as you will have to recursively search through path’s and delete.
  • Caching with SqlLite
    • Pros:
      • Can be substantially faster than a full-blown RDBMS
      • All data is stored in a normal file in the host’s file system.
    • Cons:
      • Can only support one writer at a time, which can cause high file system latency, which is inconvenient if there are many clients trying to access it simultaneously.
  • Caching with APC
    • Pros:
      • Makes PHP faster for you through the so called opcode caching.
      • No special configuration required.
    • Cons:
      • Practically none
  • Caching with Memcached
    • Pros:
      • Allows machines to pool their memory together as one large memory cache, perfect for large websites.
      • Cross platform and cross RDBMS
    • Cons:
      • Stores data in the RAM, not ideal for small systems
      • Is considered to be a volatile in-memory key/value store
  • Caching with Redis
    • Pros:
      • Can act like memcached as a key/value store however it’s really a data structure server.
      • Persistence to disk, by default.
      • Values up to 512MB in size
      • Built in clustering
      • Extremely fast at everything
    • Cons:
      • The more objects you put in it, the more memory its going to use.

So as you can see there are a bunch of different systems that handle caching in arguably better or worse ways depending on how big your website is. Putting a small website on Redis is probably overkill, you might already have set up a RDBMS solution and now not want to change to a key value store etc.

This is where StashPHP comes in, you basically use the StashPHP library to cache things like so:

First you setup the driver to use, lets just use File System for the moment:

<?php 
// Create Driver with default options
$driver = new Stash\Driver\FileSystem(); 
$driver->setOptions(array());

// Inject the driver into a new Pool object.
$pool = new Stash\Pool($driver);

Now you can setup your by wrapping the following code around your code:

<?php 
// Get a cache item.
$item = $pool->getItem('path/to/item');

// Attempt to get the data
$data = $item->get();

// Check to see if the data was a miss.
if($item->isMiss())
{
    // Let other processes know that this one is rebuilding the data.
    $item->lock();

    // Run intensive code
    $data = codeThatTakesALongTime();

    // Store the expensive to generate data.
    $item->set($data);
}

// Continue as normal.
useDataForStuff($data);

Later on when you decide to add another cache, rather than needing to go rewrite all your caching calls etc. you can just change the setup of the drivers like so:

<?php 
$subDrivers = array(); 
$subDrivers[] = new Stash\Driver\Apc(); 
$subDrivers[] = new Stash\Driver\FileSystem(); 
$subDrivers[] = new Stash\Driver\Memcached(); 
$options = array('drivers' => $subDrivers);
$driver = new Stash\Driver\Composite($options);

$pool = new Stash\Pool($driver);

This saves you a bunch of time and allows testing what suits your application best.


Posted on September 08, 2015

Being a PHP Developer in 2015

Generic coding image

This is just some thoughts on being a PHP developer in 2015.

A standard web project before used to just require you to setup a local web server, and then you’d upload to a standard web host with some worries about PHP versions perhaps but little to no thought required for the server side of things.Frameworks were a new thing, CodeIgniter was (to me at the time) the best thing to happen to PHP, introducing me to PHP MVC patterns, easily integrated vendor libraries (I never got into Zend Framework) and Twig .

Now a web project involves using programs such as Composer, Bower and Grunt just to manage project dependencies. Then you have PHP & JS frameworks like Symfony , Laravel, AngularJS that have really made life so much easier for us developers. Of course this all comes at a cost of having to put in time into learning all these new frameworks and tools, but the benefits of doing so are just amazing; development time goes way down and you create much better products. I wish I could further go into the benefits of each but they all require posts of their own to really get across their individual uses, I’ll attempt to get to that!

Working with UNIX servers is pretty standard for most web developers now, myself included. I’ve been using DigitalOcean for all my hosting, they really are a great host and I recommend them to anyone searching. Anyway a tool I found lately for server management which I guess is what has caused this post is Ajenti , before this I was using ISPConfig for the aim of being able to manage my servers easier than via ssh, however I found it’s interface pretty clunky and just overall slow, always ending up in ssh. After testing Ajenti in a fresh droplet I changed completely over to it on my other servers, so far it’s been amazing, I’m still using ssh here and there but overall Ajenti has really solved my problem so thanks guys. The install was amazingly simple too I recommend anyone looking for a GUI for their server to check it out.

So there seems to be a lot more to PHP web development now in 2015 than there was just a few years ago, though I personally feel all of it is for the better, making my life easier. It makes me wonder what it will be like in another few years though, whats next?


Posted on January 27, 2015

Apache Localhost Rendering Slowly?

Slowweb-2.jpg Is your localhost taking longer than expected to load?

A possible quick fix is to edit your httpd.conf file and set 'ServerName' to 127.0.0.1:80 . This can make the difference between millisecond load times and crying while Apache tries to load.

# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
ServerName 127.0.0.1:80

Posted on November 03, 2014

Populating a Form with a dropdown (jQuery)

I thought I’d share this, maybe it’ll help somebody else. Basically this will take the value of the drop down (select) and show() that many input fields.

Javascript

$(document).ready(function(){
        $("select[name=example]").change(function () {
        $(".hidden_input").hide();
        var cnt = $("select[name=example]").val();  
            
            while(cnt > 0) {
                $(".hidden_input#"+cnt).show();
                cnt--;  
            }
            
        });
     
});

HTML/CSS

<style>
.hidden_input{
    display: none;
}
</style>
<form>
    <select name="example">
        <option value="1">1 Guests</option>
        <option value="2">2 Guests</option>
        <option value="3">3 Guests</option>
        <option value="4">4 Guests</option>
        <option value="5">5 Guests</option>
        <option value="6">6 Guests</option>
    </select>
</form>
<div id="1" class="hidden_input">1<input name="former" type="text"></div>
<div id="2" class="hidden_input">2<input name="former" type="text"></div>
<div id="3" class="hidden_input">3<input name="former" type="text"></div>
<div id="4" class="hidden_input">4<input name="former" type="text"></div>
<div id="5" class="hidden_input">5<input name="former" type="text"></div>
<div id="6" class="hidden_input">6<input name="former" type="text"></div>

Posted on February 05, 2012

CSS Code for Wrapping Long URLs and Text

Ran into a problem last night where a long email was messing up a design in smaller screen resolutions.

Perfect fix down below:

pre {
white-space: pre; /* CSS 2.0 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3.0 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP Printers */
word-wrap: break-word; /* IE 5+ */ }

Thanks to perishable press for this one, read more about it here .


Posted on October 04, 2011