«
»

CakePHP, Chris' Brain, PHP

A Glimpse Inside CakePHP 1.2:

09.04.07 | 6 Comments

One of my co-workers over at CDC (the mighty gwoo) gave a talk to the Orange Country PHP group about CakePHP 1.2 and some of the features that it contains. One of the more interesting items, well interesting to *me* anyway, is the addition of a convenience feature to "has and belongs to many" associations called "with". Stolen directly from gwoo's slides, here's an example of it:

PHP:
  1. <?php
  2. class Post extends AppModel {
  3. var $hasAndBelongsToMany = array(
  4.  ‘Tag’ => array(
  5.  ‘className’ => ’Tag’,
  6.  ‘with’ => ‘TaggedPost’,
  7.  )
  8.  );
  9.  
  10.     function beforeSave() {
  11.          if(!empty($this->data[‘Tag’])) {
  12. $this->TaggedPost->save($this->data[‘Tag’]);
  13.          }
  14.     }
  15. }
  16. ?>

So what is the "with" parameter really for? It's nothing more than a convenience parameter that lets you apply a label to the name of your join table, so you don't have to call it by it's ugly name, in this case PostTags. Want to see it in action?

PHP:
  1. <?php
  2. class PostsController extends AppController {
  3. var $name = ‘Posts’;
  4. function tags() {
  5. $this->set(‘tags’, $this->Post->TaggedPost->findAll());
  6. }
  7. }
  8. ?>
  9.  
  10. <?php
  11. foreach ($tags as $tag) :
  12. echo $tag[‘Post’][‘title’];
  13. echo $tag[‘Tag’][‘name’];
  14. echo $tag[‘TaggedPost’][date];
  15. endforeach;
  16. ?>

It's little touches like that, unseen by a lot of developers, that makes CakPHP just a little bit easier to use with each passing day. You can download gwoo's slides here.

6 Comments


«
»