Traits for PHP

Via blog, found a link to a proposal for Traits in PHP. I wasn’t familiar with the practice, but as I read the proposal it struck a cord with me. I have been grappling with how to reuse certain functionality throughout disparate classes.

I looked at Mixins, which I also have been playing around with in JavaScript. Problem is, how do you combine a couple of mixins together. Say I am using the Zend Framework, and I have some classes that inherit from the Zend_Db_Table_Row and I want a couple to use some Mixin classes. Do I extend the Zend class for my Mixin, and extend my other classes off the Mixin? What happens if some of the classes need other functionality found in a different Mixin? Needless to say, it doesn’t seem like a great solution.

Lets jump into an example. I have a number of classes extending Zend_Db_Table_Row, and they all have a user entered attribute, like title or name, which gets turned into a SEO friendly url and saved to the database. Additionally, I don’t want the url to change, so there has to be code from preventing another developer from updating the url.For example,


<?php
class Article extends Zend_Db_Table_Row
{
    public function 
insert() {
         
$this->url $this->_createUrl();
         
parent::insert()
    }

     protected function _createUrl($name) {
       
//code to create the url - remove spaces, etc…
       
return $url
    
}
}

?>


How do I share that functionality across multiple classes, without using inheritance??

Leave a Reply