在__destruct析構函數裏操作文件出現的問題
阿新 • • 發佈:2018-08-30
操作日誌 官方 struct lse model color 測試 pac 怎麽
這幾天要給後臺加一個記錄操作日誌的功能,可是項目已經開發完了不可能再去改以前的代碼了,那有什麽快捷的方法呢?
想到了用__destruct 析構函數。
大家都知道,析構函數會在到某個對象的所有引用都被刪除或者當對象被顯式銷毀時執行。
所以應該沒問題咯,1、配置要記錄日誌的操作 2、讀取IP、get、post數據寫入庫 3.本地測試沒問題,搞定。
結果 BU G T
部署到線上之後,ThinkPHP底層報錯了:
Fatal error: Uncaught Think\Exception: _STORAGE_WRITE_ERROR_***/Runtime/Data/_fields/表結構緩存文件.php in***/Runtime/common~runtime.php:1 Stack trace: #0 ***/ThinkPHP/Library/Think/Storage/Driver/File.class.php(48): E(‘_STORAGE_WRITE_...‘) #1 [internal function]: Think\Storage\Driver\File->put(‘***‘, ‘a:9:{i:0;s:2:"i...‘, ‘F‘) #2 ***/ThinkPHP/Library/Think/Storage.class.php(37): call_user_func_array(Array, Array) #3***/hwApp/Runtime/common~runtime.php(1): Think\Storage::__callstatic(‘put‘, Array) #4 ***/ThinkPHP/Library/Think/Model.class.php(166): F(‘***‘, Array) #5 ***/ThinkPHP/Library/Think/Model.class.php(122): Think\Model->flush() #6 ***/ThinkPHP/Library/Think/Model.class.php(1454): Think\Model->_checkTableInfo() #7***/ThinkPHP/Library/Think/Model.class.php(97): Think\Model->db(0, ‘‘, true) #8 ***/Runtime/common~runtime.php(1): Think\Model->__construct( in ***/Runtime/common~runtime.php on line 1
咦?啥情況,難道沒權限?
chmod -R 777 Runtime
還報錯,難道是緩存引起的?
rm -rf Runtime
還報錯。
最後在重新看官方對該函數的說明,手冊裏有一個不太明顯的notice:
Note:
析構函數在腳本關閉時調用,此時所有的HTTP頭信息已經發出。 腳本關閉時的工作目錄有可能和在SAPI(如apache)中時不一樣。
<?php
//獲取當前工作目錄 function __destruct(){
echo getcwd(); //結果為根目錄
}
知道了問題所在,怎麽解決呢?
1、在__destruct 中使用絕對路徑操作文件
2、__destruct 之前比如構造函數內,先獲取 getcwd() 工作目錄,然後在 __destruct 中使用 chdir($StrPath) 重新設定工作目錄。 //暫未測出有其他影響
另:
<?php
//在使用Thinkphp3.23框架開發時發現下面3個Action(實現功能其實都一樣):只有aAction會觸發上述__destruct中工作目錄發生改變(使用了exit die等),而另外兩種卻不會觸發,暫時未找到原因。 function aAction(){ if(true){ //doSomeThing; exit; } //doElseSomeThing; }
function bAction(){
if(true){
//doSomeThing;
return ;
}
//doElseSomeThing;
}
function cAction(){
if(true){
//doSomeThing;
}else{
//doElseSomeThing;
}
}
在__destruct析構函數裏操作文件出現的問題