Category Archives: CakePHP

Cake DB Update Shell

Time for another useful CakePHP code example. This was created for our hosting system at work, and is used to manage DB updates on installs of the hosted websites. I have removed some code to simplify this example, mainly relating to our directory structure and to the ‘global’ database updates. Once you understand the code below, it should be relatively simple to extend it to work with other setups. We also have code to support ‘script’ updates that are held on a Task, but I’ve removed that as well.
Read more »

CakePHP, Custom Queries, and the Result Array

Note: Apparently this no longer works in Cake 2.x. I’m a little disappointed by that, but that’s the way it is.

Just a quick post about a wonderful trick I stumbled across last night while experimenting with Virtual Fields on models in CakePHP. Since I started using Cake, I’ve been annoyed that when I ran a custom query, the results would come back in the ‘[0]’ index of the result array, because Cake couldn’t tell what tablename they were from. I’d experimented with a couple different ways to alias them to try and get them to work,¬†but none of them worked. I eventually gave up, and just dealt with it.

So, last night while setting up my first virtual field, I looked at the debug log. There, I discovered this query:

    (CONCAT(`Package`.`name`, " ($", `Package`.`price`, ")")) 
        AS `Package__list_name` 
    `packages` AS `Package`

The key part to notice is the alias it gave to the CONCAT() field. ‘Package__list_name’. That allows Cake to properly identify the model that the field belongs to when retrieving the results, and it can then put it into the array properly, resulting in this array structure:

array (
  0 => 
  array (
    'Package' => 
    array (
      'id' => '1',
      'name' => 'Basic MU* Hosting',
      'price' => '5.00',
      'list_name' => 'Basic MU* Hosting ($5.00)',
  1 => 
  array (
    'Package' => 
    array (
      'id' => '2',
      'name' => 'Basic Web Hosting',
      'price' => '5.00',
      'list_name' => 'Basic Web Hosting ($5.00)',

I hope this tip is as useful to others as it will be to me. It may not seem like much, but it will be very nice to be able to place items where I want them in the result arrays.

CakePHP + Symlinks = Pain

Now that I’ve had a day or so to recover, I’m going to tell you about what I just spent 2-3 weeks trying to resolve. By way of explanation, our main product at work is a CakePHP based CMS application. It has a lot of neat features, including the ability for users to upgrade to newer versions any time they choose. We keep all versions present in /etc/precious_core/<version_number>/, and each user has a symlink to the relevant directory in their webroot.

When they upgrade, part of the process is to replace that symlink with a new on that points at their new version. For a long time we’ve known there was a problem of some kind related to CakePHP’s cache that developed after upgrades, but it was never a huge problem, so we mostly just ignored it. However, in a recent release, it started causing major problems, and I got tasked with finding and fixing the actual bug. I figured it would take a day or two, and I’d be done with it.¬†Little did I know just how painful this was going to be.

I initially tried several ways of forcing the cache to get cleared when the app was upgraded. That worked well, as far as it went, but then a new problem surfaced. At least half the time, the cache would re-populate with bad data after an upgrade. Some of the cached file paths would be for the wrong version of the central app, for no apparent reason. I tried throwing even more thorough cache clearing at it. Things got a little better, but it still wasn’t working.

Finally, I fully duplicated our production setup on my local dev machine, parallel version directories included, and installed a PHP debugger, so I could step through the code and figure out what exactly was going on. After several hours of research, I determined that the error was happening in this function:

function __map($file, $name, $type, $plugin) {
	if ($plugin) {
		$this->__map['Plugin'][$plugin][$type][$name] = realpath($file);
	} else {
		$this->__map[$type][$name] = realpath($file);

The file paths that were getting inserted into $this->__map were sometimes incorrect. I knew that realpath() could cache it’s data, but I was explicitly calling clearpathcache() during the upgrade process. So why was it getting bad paths sometimes? At this point, Ceeram (@ceeram) of #cakephp on Freenode helped me out by pointing me at this blog: PHP, symlinks, and the realpath cache, which explained perfectly what was going on.

It turns out realpath()’s cache is per-thread, so even though I was clearing it in the apache thread that was doing the upgrade, it still had old data in other apache threads. Possibly very old data sometimes. (I once saw file paths for 3 different versions of our app in one cake_core_file_map during testing.) The simplest solution that I was able to discover was to simply add an apache graceful restart during our upgrade process. The impact of a graceful restart is minimal, but it does cause all apache threads to get closed down and new ones opened, which fixes the problem by forcing all of them to clear their cache.

So, the moral of the story? Well, not sure there is one. Except that sometimes you need a breakpoint debugger even when you’re coding PHP.

Simple NaNoWriMo API Class

As anyone who knows me probably realizes (because I talk about it incessantly) it’s NaNoWriMo time again. Which means I’m revamping my wordwar tool for this year. This time, I’m giving it a complete overhaul. In the process, I looked at how I was using the API provided by NaNoWriMo, and decided I needed to improve it. After all the coding I’ve done in CakePHP in the last year, I realized there was a very very simple way to do this. Not much to say about it, so here’s the code:

class WordCountApiComponent extends Object {
	function __call($name, $arguments) {
		if (count($arguments) == 1) {
			$xml = $this->_request("".$name."/".$arguments[0]);
		} else {
			$xml = $this->_request("".$name);
		return $xml;
	private function _request($url) {
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		return new SimpleXMLElement($output);

That’s it. Just two methods. (And I could reduce it to 1, but I prefer to keep the CURL logic in it’s own method.)

Using it is just as simple. All NaNoWriMo API methods use either 0 or 1 arguments, and the method names are simply part of the URL. So, to call the ‘wc’ API, that returns the current wordcount for a single user, taking their UID as it’s only parameter, you’d do this:

$uid = 78110; // My UID
$api = new WordCountApiComponent();
$wc = $api->wc($uid);
echo $wc->uname; // "utoxin"
echo $wc->user_wordcount; // '0'

Hope this helps someone! It’s certainly a nice simple way to interface with the API.

More Correct Email from CakePHP

One problem a lot of people have with sending email from PHP in general is properly setting the envelope sender of the message, so that it’s correct in all the headers. This is important because it affects spam filtering rather drastically. Also, some ISPs and other email providers won’t even accept a message if the envelope header is set to an invalid address.

In regular PHP, this is simple to fix. Consider the following example, that sets the from address properly:

$headers = 'From:' . "\r\n" .
    'Reply-To:' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    "Test Message", 
    "This is a test message", 

The key here is that last parameter we pass to the function: ‘’. That passes a command-line option to sendmail that properly sets the envelope sender. Most people leave that off, because they don’t even realize the need it there.

Okay, so now we know how to do it in raw PHP. How do we do this using CakePHP’s email component? After all, the documentation doesn’t mention anything about that ‘additional parameters’ argument, does it? Or maybe it does. You just have to read the full API docs very carefully. It turns out, if you set the ‘additionalParams’ property of the Email Component, it will pass it on to the mail() function when it calls it. Perfect! So, here’s how to properly initialize the Email Component in CakePHP:

$this->Email->to = '';
$this->Email->subject = 'Test Message';
$this->Email->replyTo = '';
$this->Email->from = '';
$this->Email->additionalParams = '';
$this->Email->template = 'test_message';
$this->Email->sendAs = 'both';

And there you have it! The correct way to send email with proper envelope headers from CakePHP. Enjoy the lower spam score that results!