Even though I’ve been incredibly busy with freelance work over the last couple of months, I’ve somehow found time to begin work on a system for playing boardgames through the web browser. This is something I’ve wanted to do for years but it’s only now that I feel I have the knowledge to achieve it on my own. I’m using the CakePHP framework and learning a lot of it as I go.
In building a CakePHP app to learn the framework I’d been searching for about a day for the best way to retrieve data from related models. I came across the recursive attribute which returns all related data to a given depth. Using this appears to be hugely wasteful as the same data is likely to be fetched many times over so I continued to look for a better way.
I eventually found the containable behaviour buried away in the manual. After reading through a few times to get my head around the concept, it seems to be the answer to all my CakePHP worries.
You simply tell it which models to pull in at each step so you only retrieve the data you ask for. A bit of effort here will save a lot of database requests.
$this->Game->contain(array( 'Character' => array( 'User' => array( 'fields' => 'username' ) ), 'Post' => array( 'Character' => array( 'User' => array( 'fields' => 'username' ) ) ) ));
I love CakePHP. There, I said it.