我正在編寫一個REST API並需要檢查天氣中給定的模型名稱是否存在於目錄中。模型存在或不在YII中使用自定義函數 - 性能
1 - http://example.com/RestApi/index.php/api/posts/
2 - http://example.com/RestApi/index.php/api/post/
從這兩個,URL 1是不正確的URL 2是正確的(後)。所以我採取這一PARAM,做一個搜索,如下圖所示
$model = $m::model()->findAll($criteria);
$m = TK::get('model');
當$ m是不正確的,PHP警告包括(posts.php):未能打開流:沒有這樣的文件或目錄將觸發。
所以爲了避免這種情況發生,我寫了一個函數作爲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調用任何性能問題?
是YII緩存已啓用。但除此之外,這將是一個表現打擊?有沒有其他方法可以與yii做到這一點?我通過yii手冊,無法找出一個。 – dev1234
如果你的方法沒有使用Yii緩存,那麼啓用Yii緩存是無足輕重的。我還用更好的解決方案更新了我的答案。 – DaSourcerer
感謝您的更新,但它根本不幫助我。我已經評估過一次。我需要小寫兩個類名和獲取參數,並比較,因爲我在做電子函數。 – dev1234