2014-10-30 2 views
0

한 번에 한 명의 사용자 만 실행할 특정 코드가 있습니다. 나는 복잡한 잠금/세션 의존 시스템을 만들고 싶지 않습니다. 사용자 요청을 지연하여 다시 시도하기 위해 메시지를 반환하길 원합니다.데이터베이스의 트랜잭션과 같은 PHP 코드가 필요합니까?

코드는 실제로 ssh/powershell 연결이므로 분리하고 싶습니다.

거기에 할 수있는 편리한 방법이 있습니까 ??

나는 laravel/php code라는 것을 잊어 버렸습니다.

+0

당신이 우리에게 코드와 당신이 지금까지 시도하고 오류를 보여줄 수/문제를 당신은 다음 샘플 코드를 사용하여 작업 예제를 유도 할 수있다 우리가 너를 잘 도울 수 있도록 우연히 만나는가? 사용자가 코드를 어떻게 실행합니까? – llanato

답변

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

관련 문제