0


I'm dealing with database containing of many tables, with many field prefixes (two first letters of every table), so when I have users table I cannot use "name" property ($user->name) but I can use: $user->us_name.


I's there a way to simplify things and set automagic prefix for every field of a table ?

2 Answers 2

1

You'd have to extend Zend_Db_Table_Row to accomplish this. Fortunately, ZF includes a _transformColumn() method expressly for this purpose. But I'm getting ahead of myself. First, set up your table class. This assumes your database has a table called "foo_mytable":

class MyTable extends Zend_Db_Table_Abstract {
    protected $_name = 'foo_mytable';
    protected $_rowClass = 'My_Db_Table_Row';
}

Next, create your custom Row class:

class My_Db_Table_Row extends Zend_Db_Table_Row {
    protected function _transformColumn($columnName) {
        $columnName = parent::_transformColumn($columnName);
        $prefix = 'us_';
        return $prefix . $columnName;
    }
}

Now, you can do something like this (for simplicity, this example ignores MVC design ideals):

$table = new MyTable();
$records = $table->fetchAll();
foreach ($records as $record) {
    echo $record->name;
}

Assuming your table has a column named "us_name", this should work. I tested it myself. Note that in your custom table row, you might want to grab the table prefix from a config file. If you've got it stored in your registry, you could replace $prefix = 'us_'; with $prefix = Zend_Registry::get('tablePrefix');.

Sign up to request clarification or add additional context in comments.

Comments

0

I didn't know about _transformColumn(). I'm gonna hop on top of @curtisdf 's example.
I think you should override with this (not tested):

protected function _transformColumn($columnName)
{
    $tblName = $this->_table->info(Zend_Db_Table::NAME);
    $prefix  = substr($tblName, 0, 2);

    return $prefix . '_' . parent::_transformColumn($columnName);
}

Using this, you won't need to store prefixes/table-names, as they are retrieved dinamically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.