How do I check if table names are valid in Propel?

本小妞迷上赌 提交于 2019-12-13 18:12:48

问题


I want to check if a table name is valid in Propel, and then do something with it such as get its PHP name. The problem is that I am using the DatabaseMap and it only contains tables that have been instantiated. For instance:

$map = Propel::getDatabaseMap();
$map->getTableName('group'); // throws exception

If I iterate over the tables:

$tables = $map->getTables();
foreach ($tables as $key => $value) {
    echo $key;
}

It only outputs 'user'. It does not output any other tables in my database.

Are there any other methods to check if a table name is valid in Propel?


回答1:


You can parse your schema.xml with PHP's simplexml.

$xml = simplexml_load_file('schema.xml');
$tableExists = 0 < count($xml->xpath("table[@phpName='$tableName']"));

Don't forget to filter users's input for $tableName, otherwise it's possible to inject own query into xpath. To have better performance you should cache your results.

Even better would be if you create a hash map with all tables based on your schema.xml, cache this hash map and check against this every time.

$hashMap = $foo->getCache('tables');

if (!$hashMap) {
    $xml = simplexml_load_file('schema.xml');
    $tables = $xml->xpath("table");
    foreach ($tables as $table) {
        $hashMap[$table['phpName']] = true;
    }
    $foo->setCache('tables', $hashMap);
}

$tableExists = isset($hashMap[$tableName]);

In this case it's not really necessary to filter user's input.




回答2:


You could just check to see if the class exists:

if (class_exists(camel_case($table, true) . 'Query')) {
  // it exists!
}


来源:https://stackoverflow.com/questions/21052889/how-do-i-check-if-table-names-are-valid-in-propel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!