2017-02-02 29 views
1

我有一塊依賴相當片狀的第三方服務來獲取數據來呈現,所以當它遇到問題時, d喜歡顯示錯誤消息,而不是拋出異常並且不呈現頁面。具體5(5.7) - 不要緩存頁面或當前塊的塊錯誤

很容易做,直到你來阻止/頁面緩存。數據的使用壽命很長,所以當找到時,可以緩存所有內容。但是,如果不是,頁面會緩存並顯示錯誤消息。因此,我需要告訴CMS不要將塊或頁面輸出保存到緩存中。

實施例的代碼(塊控制器內):

public function view() { 
    try { 
     $this->set ('data', $this->getData()); 

    } catch (\Exception $e) { 
     \Log::addError ('Blockname Error: '.$e->getMessage(), [$e]); 
     $this->render ('error'); 
    } 
} 

在catch塊我試圖既$this->btCacheBlockOutput = true;\Cache::disableAll();但既不作品。有沒有辦法告訴C5不要緩存當前請求上的任何內容?

回答

0

的BlockController在具體的文件夾有這些受保護的變量設置爲標準:

protected $btCacheBlockRecord = true; 
protected $btCacheBlockOutput = false; 
protected $btCacheBlockOutputOnPost = false; 
protected $btCacheBlockOutputForRegisteredUsers = false; 

所以,如果你設置的所有這些關於你的假塊Controller.php這樣,它不應該緩存你的塊。

class Controller extends BlockController 
{ 
    protected $btCacheBlockRecord = false; 
    protected $btCacheBlockOutput = false; 
    protected $btCacheBlockOutputOnPost = false; 
    protected $btCacheBlockOutputForRegisteredUsers = false; 
    public function view(){ 
    ..... 

這將禁用塊(即使第三方連接成功)的緩存。

一種不同的解決方案是如果第三方連接未能從所述第三方接收到的數據從數據庫保存在數據庫中(例如,作爲一個JSON字符串),並加載數據...如果第三方連接成功,您可以更新數據庫中的記錄。

根據第三方服務的答案,您可以設置條件。 實施例:

//service returns on OK: 
//array('status' => 'ok') 
//service returns on NOT OK: 
//array('status' => 'nok') 

public function view() { 
    $data = $this->getData(); 
    if($data['status'] == 'ok'){ 
     //save data to database in a config value using concrete Config class 
     $configDatabase = \Core::make('config/database'); 
     $configDatabase->save('thirdpartyanswer', $data); 
     $this->set('data', $data); 
    }else{ 
     //getData function returned error or nok status 
     //get data from concrete Config class 
     $configDatabase = \Core::make('config/database'); 
     if($configDatabase->get('thirdpartyanswer')) != ''){ 
      //set data as "old" data from config 
      $this->set('data', $configDatabase->get('thirdpartyanswer')); 
     }else{ 
      //no data in config -> set error and nothing else 
      $this->set('error', 'An error occured contacting the third party'); 
     } 
    } 
} 

(上面的代碼還沒有被測試)上存儲配置值
的更多信息:
https://documentation.concrete5.org/developers/packages/storing-configuration-values

*編輯*

第三種選擇是將吹掃如果呼叫失敗,該特定頁面的緩存。

在你blockcontroller的頂部:

use \Concrete\Core\Cache\Page\PageCache; 
use Page; 

在 '如果' 時調用API失敗:

$currentPage = Page::getCurrentPage(); 
$cache = PageCache::getLibrary(); 
$cache->purge($currentPage); 

找到在:https://www.concrete5.org/community/forums/5-7-discussion/programmatically-expiring-pages-from-cache

+0

謝謝,但沒有按回答這個問題。該塊用於真正需要全頁面緩存的高流量頁面。我已經將數據保存在「昂貴」(磁盤)緩存中,這非常適合這種情況,但對頁面緩存問題沒有幫助。 –

+0

我編輯了我的回覆,請參閱'第三個'選項。我測試過,如果頁面仍然加載,所以代碼是有效的。 – Jozzeh

+0

如果從緩存中清除頁面會阻止當前渲染的輸出被緩存,那麼這是一個很好的開始,但是從快速測試來看,我仍然看到舊的塊輸出。假設這將來自塊輸出緩存,在錯誤處理中調用相關塊對象的refreshBlockOutputCache方法似乎沒有幫助。也許在這一點上手動填充塊的cacheSettings對象會有所幫助,但是當我有空時,我將不得不再玩一玩。 –