2014-10-30 28 views
0

我有一定的代碼,我想一次只有一個用戶運行。我不想讓兒子複雜的鎖定/會話依賴系統,我只是想延遲用戶請求我們返回一些消息來重新嘗試。php代碼像數據庫中的交易?

代碼實際上是ssh/powershell連接,所以我想分離它。

它有任何方便的方法嗎?

我忘了提及它的laravel/php代碼。

+0

你能告訴我們的代碼,到目前爲止,你已經嘗試過什麼,任何錯誤/問題,你可以使用下面的示例代碼中獲得一個工作示例遇到,所以我們可以幫助你更好?用戶如何運行代碼? – llanato 2014-10-30 15:35:07

回答

1

你需要獲得某種「鎖定」。如果沒有鎖定,則沒有人訪問任何內容。如果有鎖,某人正在訪問某些內容,其餘的則應該等待。最簡單的方法是使用文件和獲取排他鎖來實現這一點。我將發佈一個示例類(未經測試)和示例用法。

class MyLockClass 
{ 
    protected $fh = null; 
    protected $file_path = ''; 

    public function __construct($file_path) 
    { 
     $this->file_path = $file_path; 
    } 

    public function acquire() 
    {  
     $handler = $this->getFileHandler(); 

     return flock($handler, LOCK_EX); 
    } 

    public function release($close = false) 
    { 
     $handler = $this->getFileHandler(); 

     return flock($handler, LOCK_UN); 

     if($close) 
     { 
      fclose($handler); 
      $this->fh = null; 
     } 
    } 

    protected function acquireLock($handler) 
    { 
     return flock($handler, LOCK_EX); 
    } 

    protected function getFileHandler() 
    { 
     if(is_null($this->fh)) 
     { 
      $this->fh = fopen($this->file_path, 'c'); 

      if($this->fh === false) 
      { 
       throw new \Exception(sprintf("Unable to open the specified file: %s", $this->file_path)); 
      } 
     } 

     return $this->fh; 
    } 
} 

用法:你

$lock = new MyLockClass('/my/file/path'); 

try 
{ 
    if($lock->acquire()) 
    { 
     // Do stuff 

     $lock->release(true); 
    } 
    else 
    { 
     // Someone is working, either wait or disconnect the user 
    } 
} 
catch(\Exception $e) 
{ 
    echo "An error occurred!<br />"; 
    echo $e->getMessage(); 
} 
+0

可能是一個解決方案,謝謝.. – mariotanenbaum 2014-10-31 14:00:17