2013-11-22 14 views
1

我正在編寫一個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調用任何性能問題?

回答

1

爲什麼不直接在你的項目中地圖的所有類的。這樣你就可以使用它而不是一直查看磁盤。請參考composer。是的,我知道這是一個依賴管理器,但它也是一個很好的autoload generator

如果正確地與添加composer.json例如:

"autoload": { 
    "classmap": [ 
     "protected/", 
    ] 
} 

在它,它會自動生成一個完整的類圖陣列,其可以從供應商/作曲家/ autoload_classmap.php加載。所有你需要做的就是確保數組的鍵是小寫的,你可以在1上匹配1。如果你添加新的類,請記得調用「composer dump-autoload」來確保

如果你這樣做,只考慮加載完成自動加載,而不是(供應商/ autoload.php),因爲它會幫助Yii中作爲一個整體來限制磁盤搜索。讓Yii從中獲利更多:

$loader = require(__DIR__ . '/../vendor/autoload.php'); 
Yii::$classMap = $loader->getClassMap(); 

在調用run()函數之前,在您的index.php中。 那樣,Yii也可以在數組中查找類。

對於您的問題,只需調用$裝載機> getClassMap()函數的第二時間和小寫數組鍵爲您查找表。

1

由於代碼中循環內有相當多的與文件系統相關的函數,所有發出的系統調用都會導致性能下降。你至少應該緩存你的方法的結果。

一個更好的方法可能是this solution提出了通過Yii的核心開發:)

+0

是YII緩存已啓用。但除此之外,這將是一個表現打擊?有沒有其他方法可以與yii做到這一點?我通過yii手冊,無法找出一個。 – dev1234

+0

如果你的方法沒有使用Yii緩存,那麼啓用Yii緩存是無足輕重的。我還用更好的解決方案更新了我的答案。 – DaSourcerer

+0

感謝您的更新,但它根本不幫助我。我已經評估過一次。我需要小寫兩個類名和獲取參數,並比較,因爲我在做電子函數。 – dev1234

相關問題