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.
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




