2011-11-02 69 views
1

我是Cake的shell開發新手。我面臨的問題是在腳本本身設置數據源。我的database.php是;CakePHP Shell腳本環境設置

function __construct() 
{ 
    if(getenv('ENVIRONMENT') == 'staging') { 
     $this->default = $this->staging; 
    } else { 
     $this->default = $this->production; 
    } 
} 

所以,我正在設置基於Web服務器的環境設置數據庫。當然,php-cli不能訪問這個變量。我最終做的是創建一個cakephp shell任務。

class SelectEnvTask extends Shell { 

    public function execute() 
    { 
     App::Import('ConnectionManager', 'Model'); 
     $configs = ConnectionManager::enumConnectionObjects(); 

     if (!is_array($configs) || empty($configs)) { 
      $this->out('Error! No database configuration has been found.'); 
     } 

     $connections = array_keys($configs); 

     if(!isset($this->args[0])) { 
      $this->out('Error! Please enter one of the environment settings as an argument: ' . implode('/', $connections) . 
       "\n\n" . 'eg. ./Console/cake *script_name* *environment*', 2); 
      exit(1); 
     } 

     if(!in_array($this->args[0], $connections)) { 
      $this->out($this->args[0] . ' environment could not be found!', 2); 
      exit(1); 
     } 

     //hacky solution until finding a better one 
     $models = App::objects('Model'); 
     foreach($models as $model) { 
      ClassRegistry::init($model)->setDataSource($this->args[0]); 
     } 
    } 
} 

這工作正常,但是當你在看到下面的任務中,我得到的所有型號名稱和改變他們的數據庫連接,這是不是一個好的做法。我也不想在數據庫類中設置更多變量,並希望在shell/tasks中處理這些變量。

有沒有更好的方法來實現這個目標?

謝謝,

+0

嘿merinn,做你會得到答案嗎?我對此持懷疑態度。如何實現基於服務器環境的優雅解決方案,滿足Web和控制檯的需求。 – Junior

回答

0

這是一個更加優雅的解決方案。下面的方法添加到您的外殼或任務,然後執行它,只要你需要,以更改數據的個人資料上飛(在app /配置/ database.php中列出):

function change_database_profile($database = 'default') { 
    $connected = ConnectionManager::getDataSource($database); 
    if($connected->isConnected()) { 
     return true; 
    } 
    return false; 
} 
相關問題