How to use inheritance for cake models

Sep 21, 2006
This was brought up in the google group and a similar topic was mentioned on cakebaker's blog:

The Problem

  • You get a job modifying a client's existing database-driven web application.
  • You decide to use cakePHP, but it must exist along side some legacy code.
  • The database has a repeated structure in some tables.
  • You don't have the option to change the structure of the database.
This is a similar situation to the one brought up in the google group. Some of the tables in the database have identical structures, so your cake models will end up looking alike, which isn't very DRY. It would nice for us if cake allowed one model to work with multiple tables, but it doesn't. Since we can't modify the database, how do we keep our models DRY?

The My Solution

Object-oriented programming allows for the idea of inheritance, in which one class inherits the properties and behaviors of another "parent" class. This creates a parent-child relationship in which one change to the parent makes a cascading change to all its children. Since we want one model to handle a few similar tables, using inheritance seems like a good approach.

First, we need a parent model to handle the structure of our similar tables. Since "parent" is a reserved word in PHP, I'll stick with using "mom": File: app/models/mom.php

<?php
class Mom extends AppModel {
    var $validate = array('columnName' => VALID_NOT_EMPTY);

    function someSharedMethod() {
        // do something here...
    }
}
?>
Now we've got our Mom model that contains the code which applies to all our similar tables. But we're not done yet. To follow cake convention, we need to create models for each table we want to use. But cake doesn't know about our Mom model we want to inherit from, so we need to tell our app to use it. We do this with PHP's require statement.
File: app/models/child.php

<?php
require(APP . DS .'models'. DS .'mom.php');

class Child extends Mom {
    var $name = "Child";
}
?>
Now our Child model holds all of the code we wrote in Mom, and we also managed to follow cake conventions so everything should tie itself together properly.

Summary

The solution may be a bit clunky, but it's certainly cleaner than copying all the code into each model (and any changes you make in the future). It's a nice way to take advantage of object-oriented programming, and only a slight nudge was needed for it to work with cakePHP. Please let me know if some one comes up with a better solution, but I think this'll work for now.
0 comments

More Posts

Other Places

Recent Photos

image image image image image image