【发布时间】:2013-11-22 10:27:33
【问题描述】:
我正在编写一个 REST API,需要检查目录中是否存在给定模型名称的天气。
1 - http://example.com/RestApi/index.php/api/posts/
2 - http://example.com/RestApi/index.php/api/post/
从这两个中,URL 1 不正确,URL 2 正确(post)。所以我正在使用这个参数并进行如下搜索,
$model = $m::model()->findAll($criteria);
$m = TK::get('model');
当 $m 不正确时,PHP 警告 include(posts.php): failed to open stream: No such file or directory will trigger.
为了避免这种情况发生,我编写了一个函数作为 modelExists() 并像下面这样使用它。
If (!TK::modelExists($m))
$this->sendResponse(false, 1003);
函数体如下,
/**
* Checks for a given model name
* @param string $modelName is the name of the model that is used to search against the directory.
* @return String $result, the name of Model. if doesnt exist NULL;
*/
public static function modelExists($modelName)
{
$result = null;
$basePath = Yii::getPathOfAlias('application').DIRECTORY_SEPARATOR;
$modelsDir = 'models'.DIRECTORY_SEPARATOR;
$modelName = strtolower($modelName).'.php';
$generalModelDir = scandir($basePath.$modelsDir);
foreach ($generalModelDir as $entry) { // Searching in General model directory
if ($modelName == strtolower($entry)) {
$temp = explode('.', $entry); // array('User','php')
$result = $temp[0];
break;
}
}
if (!$result) {
$modulePath = $basePath.'modules'.DIRECTORY_SEPARATOR;
$moduleDirectory = scandir($modulePath);
foreach ($moduleDirectory as $dir) {
$subModuleDirectory = scandir($modulePath.$dir);
foreach ($subModuleDirectory as $entry) {
if (is_dir($modulePath.$dir.DIRECTORY_SEPARATOR.$entry)) {
$directories = scandir($modulePath.$dir.DIRECTORY_SEPARATOR.$entry);
foreach ($directories as $subDir) {
if ($modelName == strtolower($subDir)) {
$temp = explode('.', $subDir); // array('User','php')
$result = $temp[0];
break;
}
}
}
}
}
}
return $result;
}
我的问题是:这会导致任何性能问题,因为我正在检查每个 API 调用吗?
【问题讨论】:
标签: php web-services api rest yii