views:

119

answers:

1

Simple one hopefully, is there a specific way i should be updating a single database value using a model in Zend Framework.

I currently do this:

class Model_MyModel extends Zend_Db_Table_Abstract
{
    $_name = 'table';
    public function updateSetting($id,$status)
    {
        $data = array(
            'status' => $status
        );
        $this->update($data, 'id = '.$id);
    }
}

$update = new Model_MyModel();
$update->updateSetting(10,1);

Obviously i could pass in another argument as the column to update. I just wondered if there was a more "magic" way i should be doing this?

+1  A: 

You could write a simple property overloader for this:

class Model_MyModel extends Zend_Db_Table_Abstract
{
    protected $_name = 'table';

    /**
     * Should be  a Zend_Db_Table_Row instance
     * 
     * @var Zend_Db_Table_Row 
     */
    protected $_currentRow = null;

    /**
     * Property overloader
     * 
     * For more information on this see 
     * http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
     * 
     * @param string $key
     * @param string $value
     * @return void
     */
    public function __set($key, $value)
    {
        $row = $this->getCurrentRow();
        if (null !== $row)
        {
            $row->$key = $value;
        }
        else
        {
            throw new Exception('Cannot update a column on a non existent row!');
        } 
    }

    /** 
     * Save current row
     * 
     * @return Model_MyModel
     */
    public function saveCurrentRow()
    {
        $row = $this->getCurrentRow();
        if (null !== $row)
        {
            $row->save();
        }
        else
        {
            throw new Exception('Cannot save a non existent row!');
        } 
    }

    /**
     * Set current row
     * 
     * @param Zend_Db_Table_Row $row
     * @return Model_MyModel
     */
    public function setCurrentRow(Zend_Db_Table_Row $row)
    {
        $this->_currentRow = $row;
        return $this;
    }

    /**
     * Get current row
     *
     * @return Zend_Db_Table_Row
     */
    public function getCurrentRow()
    {
        return $this->_currentRow;
    }
}

You could then do stuff like this:

$model = new Model_MyModel();
$model->status = 'foo';
$model->somecolumn = 'bar'
$model->saveCurrentRow();

Although this approach would require the least editing in your code, an even better approach would be seperating your models from your database tables and use a Data Mapper Pattern as described in the Quickstart.

Aron Rotteveel