dallin
dallin

Reputation: 9426

Creating a class to map column names in new tables to legacy tables

We recently updated all our database tables to use a uniform naming convention (our old tables were a mess). In some cases, we will still need to communicate between our legacy tables and our new tables. I have been tasked with writing a class that translates the old table and column names to the new ones AND vice versa.

Ideally, I would have a bidirectional array to do this, but I don't think that exists in PHP. So I personally can think of the following two ways to do this:

  1. Just write out two large arrays, one mapping old names to new and one mapping new names to old.

  2. Create the two arrays dynamically on object creation from a single list

Is there any other way to do this and what are the advantages and disadvantages of each way?

Upvotes: 0

Views: 313

Answers (2)

dallin
dallin

Reputation: 9426

What I ended up doing was creating a class with a variable called newToOldArray and listing out the array with the new names as the key and the old names as the values right there in the code. So I didn't have to write out the entire array again in reverse to create oldToNewArray, I used the php function array_flip() (which I just found) in the constructor to create the other variable.

This approach allows me to not have to worry about the two arrays becoming out of sync if I changed a value in one but not the other. It also saves on file size and the time to type it out again. I can also look at that single table as a reference whenever I need to.

Upvotes: 0

bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

I suppose I would send a parameter to a function that tells what db is going to be used, and assign values that is used for new db and assign other values when legacy db is going to be used.

<?php
function dosql($newDb = true) {
   if ($newDb === true) {
       //Fields used when using new db
       $fieldArray = array('id', 'another field');   
       $tableName = 'newTable';
   }
   else {
       //Fields used when using old db
       $fieldArray = array('old_id', 'another old field');
       $tableName = 'oldTable';
   }

   //example - would be select id, another field from newTable where id=5 if $newDb = true
   $sql = "select " . implode(',', $fieldArray) . " from " . $tableName . " where " . $fieldArray[0] . " =5"; 

  //And of course do the actual db-operations...

}
?>

Upvotes: 1

Related Questions