Skip to content

A dummy datasource for CakePHP

I was recently developing a project at work which at the beginning didn’t need a database. However, Cake was still testing the database connection and issuing a warning as a result when it couldn’t connect. My solution was to create a dummy datasource which silenced the warnings and allowed me to get on with the rest of development in relative peace.

The scope of the project changed and a database was required. The dummy datasource had to go so I thought I’d share it here before it was thrown to the winds.

Here’s the datasource, which belongs in models/datasources/dbo/dbo_dummy.php:

<?php
class DboDummy extends DboSource {
 
        function connect(){
                $this->connected = true;
                return true;
        }
 
        function disconnect(){
                $this->connected = false;
                return true;
        }
 
}
?>

To use the datasource use the following in your config/database.php:

<?php
class DATABASE_CONFIG {
 
        var $default = array(
                'driver' => 'dummy',
                'host' => '',
                'login' => '',
                'password' => '',
                'database' => '',
        );
 
}
?>

Enjoy!

Migrating a WordPress database between domains

Occassionally I find myself developing a WordPress theme which will then require moving from development into production or otherwise having to move a blog between domains.

Apart from the transfer of the files, including plugins, theme and core WordPress installation, there is only 1 slightly gotcha: the database. I’ve never been quite sure why but WordPress stores the URL of the blog in it’s database, not once, but twice. For the blog to be migrated the database needs a slight tweak.

As always, create a backup before doing anything. This can be done with phpMyAdmin or using the mysqldump command like so:

$ mysqldump -uUSER -pPASSWORD DATABASE > /path/to/backup.sql

If the database is to be hosted on a different machine you can then import this dump using using which ever method you’re comfortable with. Finally, run the following query on the database, subsituting your own domain name:

UPDATE
	wp_options
SET
	option_value = 'http://DOMAIN.TLD'
WHERE
	option_name IN ('siteurl', 'home');

That’s it!

MySQL database backup with remote storage

Prevent a disaster

After reading Jeff Atwood’s backup failure last month I decided to finally get around to doing something I’d been intending to do “one of these days” but had in actual fact been putting off for years.

Here’s the steps I took to ensure the databases on my webserver were backed up every night and copies of the dumps stored remotely.

On the remote storage machine

Generate an ssh key pair with and empty password and put the public key on the remote server. This will give our script access to the server without requiring you to enter a password each time:

$ ssh-keygen -t rsa -f /home/steve/code/db_backup/id_rsa
$ scp /home/steve/code/db_backup/id_rsa.pub REMOTEHOST:

This script will fetch all the backups, logging in as the rsync user and using the private key just generated. It’s located at /home/steve/code/db_backup/sync_backups.sh:

#!/usr/bin/env bash
rsync -e "ssh -l rsync -i /home/steve/code/db_backup/id_rsa" -avz REMOTEHOST:mysql/ /data/primary/backup/mysql/

Have this happen automatically daily at 12:20am:

$ crontab -l
# m h dom mon dow command
20 0 * * * /home/steve/code/db_backup/sync_backups.sh
$

On the machine to be backed up

Create a new user and allow ssh access with the previously generated key:

# adduser rsync
# mkdir ~rsync/.ssh
# mv ~steve/id_rsa.pub ~rsync/.ssh/authorized_keys
# chown rsync:rsync ~rsync/.ssh/authorized_keys
# chmod 400 ~rsync/.ssh/authorized_keys

This script will dump all available databases and is located at /root/bin/backup_databases.sh:

#!/usr/bin/env bash
 
# dump all available databases
# SJW
 
AUTH='-uroot -pROOTPASSWORD'
DBS=`mysql $AUTH --skip-column-names -e 'SHOW DATABASES;'`
BACKUPS='/home/rsync/mysql/'
 
for DB in $DBS
do
	mysqldump $AUTH $DB > $BACKUPS`date +%Y%m%d%H%M`_$DB.sql
done
 
# delete backups older than 5 days
find $BACKUPS -mtime +5 -type f | awk '{print "rm "$1}' | sh

Have the script run nightly at 12:10am via cron:

# crontab -l
# m h dom mon dow command
10 0 * * * /root/bin/backup_databases.sh
#

Closing thoughts

This approach is realtively straight forward, everything happens automatically and it could easily be extended to cover mailboxes, source code repositories, uploaded content etc. However, for mission-critical databases master-slave replication may be more appropriate. For further reading you may enjoy JWZ’s thoughts on backups.

6 months of Rehab

I find it hard to believe, but I crossed the 6 month milestone at Rehab this week.

The time has went in quickly, with a fast-pace and quick turnaround times being the norm. The vibe in the office has been great, with a decent soundsystem pumping out dance music all day and my producer Gary, aka DJ Gary Quinn, dropping in a few choice chunes.

The guys here have a real passion for the web and enjoy a good laugh, for instance, this week we had a challenge to wear a different hat each day. Here’s Iain and Jurgen in their full cowboy glory:

I spend most of my days wrangling CakePHP, the PHP framework I started developing with nearly 3 years ago now. I also do most of the administration of the Linux boxes used to host the client sites and automate as much as I can with handy bash scripts, all from the comfort of this shiny iMac:

On the downside the standard working hours are 9 to 6, which is longer than I’m accustomed to. You can’t have it all ;)

Mashing up Twitter Trends and Google Images

I recently released the latest entry in my series of nano-apps.

As with my previous efforts, istrending.com serves serves no real purpose other than as an act of deliberate practice: going through the process of coming up with an idea, writing code, registering domain names, setting up Cron jobs and configuring deployment systems to get it all up and running in a production environment.

I questioned why I was even bothering with an app that was likely not going to see any traffic or be of use to people and when I hit a minor javascript problem the project was shelved for a few months. I recently had a fresh burst of enthusiasm though and got the usual sense of achievement when I deemed the code “ready enough” and a quick cap deploy took care of the rest.

The main problem I’ve faced with this app concerns the script used to update the list of trending topics: the Twitter search api has a known issue of returning HTML instead of JSON, which has on occasion caused my inbox to be filled with emails from the Cron daemon alerting me to failed jobs. I’m also not very happy with how the javascript carousel functions, so there’s some scope for improvement there.

The code is available on GitHub as usual.

Next up is probably something bigger, very likely involving Rails. I’ve been reading up on the various testing methodologies used in the Ruby world and have written my first set of RSpec tests so I hoping my next release will at least have some test coverage. Other than that I’ll just have to see what ideas come to mind between now and then.

Any suggestions on what I should do next?

5×5 strength training program

Since my last update strength training I’ve progressed from 3 sets of 5 reps to 5 sets of 5 reps: the infamous 5×5.

I’m still training 3 days a week, Monday, Wednesday and Friday before work, still not doing any cardio and the Osgood Schlatters is still giving me gip.

Here’s what my routine has been like lately:

  • Monday
    • Front Squat
    • Overhead Press or Dumbbell Bench Press
    • Clean
  • Wednesday
    • Front Squat
    • Overhead Press or Dumbbell Bench Press
    • Barbell Row
  • Friday
    • Front Squat
    • Overhead Press or Dumbbell Bench Press
    • Deadlift

I’m training the front squat every session and alternating the overhead press and the dumbbell bench press between sessions. Taking into mind my knee difficulties I’m training the squat with relatively low intensity and wearing a knee sleeve which is giving me a much needed opportunity to work on my form and control.

As an aside, I’ve been working towards another goal: making it into the light-heavyweight division. It’s been tough going, I’m sick of the sight of food a lot of the time and have even been supplementing with vitamin B12 to see if I can boost my appetite sufficiently. I’ll be sure to let you know if I hit this milestone :D

Developer Rehab

My unemployment is over! Last week I started as a developer with Rehab Studio. Code on!

Because everyone needs their own URL shortening service

At the moment I’m in between paid work and have been using my time to generally enjoy life but to also improve my skills. I’m all about the skills.

As an act of deliberate practice to hone my skills with web-application development and to deepen my understanding of the Rails framework I’ve been adding to my collection of nano-apps.

A while back I had an idea to develop a URL shortener just to see how little code would be required but decided the world really didn’t need another one. With time on my hands over Easter & the curiosity of a technology entusiast I just started hacking and had a functioning prototype within a short time-frame.

I wasn’t keen on parting with my shiny pennies for a domain name considering my lack of income but I’d written the code and thought I’d may as well go the whole hog and get my work into the wild.

So, without further ado, I present io.gd . As usual, code is available on GitHub.

Finally, after 2 and a half years, my Rails DVD catalogue is go

Well, it only took me 2 and a half years but I finally used Rails to develop a catalogue for my DVD collection.

The catalogue loosely fits in with my series of nano-apps and is hosted on movies.stevenwilkin.com. The code is publicly available on GitHub for anyone who’s interested.

All’s left now is to actually use the system and fill in the details of my collection!

An experiment with Sinatra, HAML and Blueprint CSS

In my last post I considered transforming stevenwilkin.com into a Sinatra app.

Well, I did it, although I’m only mentioning it now.

Not only was this my first experience with Sinatra but I also decided to try using HAML for the markup and Blueprint CSS to help with the styling. If I’m going to play with a new technology why not play with a few new technologies?

I found Sinatra quite straight forward: you match up a HTTP verb (eg ‘GET’) and a url (eg ‘/’) with a block of Ruby and the results can be sent directly to the browser or an optional view template can be rendered. Simple!

Instead of a Model-View-Controller pattern like many of us are accustomed to, Sinatra provides more of a Controller-View setup which I believe would make it more suited to smaller apps which don’t necessarily make use of a database or where a full-stack framework like Rails would be overkill. If I create any more nano-apps in the future I’ll more than likely use it again.

What really struck me during this experiment and made the whole thing worthwhile was HAML. The simplicity and clarity of it’s syntax was super refreshing and meant I had to do a lot less typing and didn’t have to remember to close divs etc, never mind it being white-space sensitive! All Ruby-based web development I’ve done since has used it.

I wasn’t fussed on Blueprint. I found having a grid background during the *ahem* design phase to be great but I probably didn’t make enough use of it’s features for it to really shine through. In terms of styling and CSS I didn’t take much time to look at SASS and didn’t use it, but I’ve since reread the documentation and may well make use of it in the future.

The app was deployed onto Passenger, like my previous experiments. It took a small bit of google-fu to get the Capfile and Rack configuration tweaked correctly but once this was done pushing the code into production with Capistrano was a breeze. How did I ever survive without Capistrano?

The deeper I get into Ruby the cruder PHP seems, not to mention C#. The future seems exciting.