Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
sn01615 committed Dec 21, 2019
1 parent a71aa16 commit 9c2330d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

### 局限性
只能在同一台服务器内生效
需要临时目录写入权限
(会在临时目录创建一个 _PHP_FileLock_xxx 类似的文件)

### Install

Expand All @@ -13,5 +15,15 @@ composer require sn01615/file-lock

```php
use PhpUtils\FileLock;
FileLock::lock('lockKey');

# Get lock
$status = FileLock::getLock('lockKey');
if ($status) {
# Get lock success
} else {
# It's locked.
}

# Unlock
FileLock::unlock('lockKey');
```
14 changes: 13 additions & 1 deletion src/FileLock.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ class FileLock
private $lockFile;

public static function lock($tag)
{
self::getLock($tag, true);
}

/**
* @param string $tag Unique identification
* @param bool $die Failed to acquire exclusive lock is whether to execute die()
* @return bool If get exclusive lock fail return false, else return true.
*/
public static function getLock($tag, $die = null)
{
if (!self::$prefix) {
self::$prefix = sys_get_temp_dir() . '/_PHP_FileLock_';
Expand All @@ -23,10 +33,12 @@ public static function lock($tag)
file_put_contents($filename, time());
self::$fp = fopen($filename, "r+");
if (!flock(self::$fp, LOCK_EX | LOCK_NB)) {
die(0);
if ($die) die(0);
return false;
}
self::$instances[$tag] = new static();
self::$instances[$tag]->lockFile = $filename;
return true;
}

public static function unlock($tag)
Expand Down

0 comments on commit 9c2330d

Please sign in to comment.