开发者

How to make Doctrine delete table prefixes from class names?

开发者 https://www.devze.com 2022-12-12 14:33 出处:网络
I\'m using Doctrine 1.1.5 and I\'d like to know if there is some option for remove table prefix from files and class names when calling Doctrine::generateModelsFromDb or Doctrine::generateModelsFromYa

I'm using Doctrine 1.1.5 and I'd like to know if there is some option for remove table prefix from files and class names when calling Doctrine::generateModelsFromDb or Doctrine::generateModelsFromYaml.

Edit: For example I have tables like mo_article, mo_l开发者_如何学Canguage, mo_article_text, etc. When Doctrine generates the models (using the functions from above), the class names will be MoArticle, MoLanguage, MoArticleText, ... but I want them to be Article, Language, ArticleText... Is there some option in those functions to avoid adding table prefixes in model class names?

Thank you


I had this exact same scenario and ended up writing my own function to solve it. This function goes through my YAML file, reads each table name, and adds the appropriate className: entry without the table prefix.

Here's the function:

const TABLE_PFX = 'tableName:';
const CLASS_PFX = 'className:';

function AddClassNames($yamlPath) {

  $tempFilePath = $yamlPath . '.old';
  rename($yamlPath, $tempFilePath);
  $tempFile = fopen($tempFilePath, 'r');
  $yamlFile = fopen($yamlPath, 'w');

  while (!feof($tempFile)) {
      $line = fgets($tempFile);
      fwrite($yamlFile, $line);
      if ($index = strpos($line, TABLE_PFX)) {
          $tableName = trim(substr($line, $index + strlen(TABLE_PFX) + 1));
          $className = substr($tableName, 4);
          $className = strtocamel($className);
          $classLine = str_replace(TABLE_PFX, CLASS_PFX, $line);
          $classLine = str_replace($tableName, $className, $classLine);
          fwrite($yamlFile, $classLine);
      }
  }
  fclose($tempFile);
  fclose($yamlFile);
  unlink($tempFilePath);
}

And here's how I use it:

Doctrine_Core::generateYamlFromDb($yamlPath);
AddClassNames($yamlPath);
Doctrine_Core::generateModelsFromYaml($yamlPath, 'models',
    array('doctrine'), 
    array('generateTableClasses' => true,));

One further note - with this method you don't have the luxury of Doctrine converting your database_table_name to the PHP-friendly ClassName, so you have to do this yourself. I used the strtocamel function from here.


Just add

className: CorrectName

to each table definition you need to change in your schema.yml file. Doctrine will generate all the files with the CorrectName pattern but still read/write from your prefixed table.

0

精彩评论

暂无评论...
验证码 换一张
取 消