Search code examples
phpsymfony1symfony-1.4propel

How can I use one method with several Propel models in Symfony 1.4?


I have a method for getting all the rows from a table in the database with the order specified in the arguments:

public static function getAllOrderedBy($orders = null)
    {
        $criteria = new Criteria();
        if(is_array($orders))
        {
            foreach($orders as $column => $order)
            {
                if($order == 'asc')
                {
                    $criteria->addAscendingOrderByColumn($column);
                }
                else if($order == 'desc')
                {
                    $criteria->addDescendingOrderByColumn($column);
                }
            }
        }
        else if($orders != null)
        {
            $criteria->addAscendingOrderByColumn($orders);
        }
        return self::doSelect($criteria);
    }

This method takes place in the PagePeer class, but I want to use it with several models, like LinkPeer or SubjectPeer. I could copy and paste this code from one model to another, but I want to ask if is there a better way to have this method available for all of these classes?

It's not a problem if the usage will change, so I'll not call PagePeer:getAllByOrder(PagePeer::TITLE) but something else, I just dont want to copy this code to every model it is used in.


Solution

  • There are two ways you can accomplish that.

    • Propel behviors. Documentation states that you can add static method to your peer classes via staticMethods()
    • Symfony Mixins. They were documented in The Definitive Guide to symfony 1.0. See Chapter 17 - Extending Symfony. In newer verions of this guide information about mixins was removed, but it seems that code of sfMixer class hasn't been changed (sfMixer in sf1.0 and sfMixer in sf1.4)