<?php
namespace
Common\Business;
class
PhpLock
{
private
$path
= null;
private
$fp
= null;
private
$hashNum
= 100;
private
$name
;
private
$eAccelerator
= false;
public
function
__construct(
$name
,
$path
='lock\\')
{
$app_path
=
str_replace
('ThinkPHP/', '', THINK_PATH);
$is_cli
= php_sapi_name();
if
(
$is_cli
== 'cli' ||
$is_cli
== 'cli_server')
{
$app_path
= trim(APP_PATH, '.');
}
else
{
$app_path
=
$app_path
. trim(APP_PATH, '.');
}
$path
=
$app_path
.'/Common/Business/lockfile/';
if
(!
file_exists
(
$path
))
{
mkdir
(
$path
);
chmod
(
$path
,777);
}
$this
->eAccelerator = function_exists(
"eaccelerator_lock"
);
if
(!
$this
->eAccelerator)
{
$this
->path =
$path
.sha1(
$name
).'.txt';
}
$this
->name =
$name
;
}
private
function
_mycrc32(
$string
)
{
$crc
=
abs
(crc32(
$string
));
if
(
$crc
& 0x80000000) {
$crc
^= 0xffffffff;
$crc
+= 1;
}
return
$crc
;
}
public
function
lock()
{
if
(!
$this
->eAccelerator)
{
$this
->fp =
fopen
(
$this
->path, 'w+');
if
(
$this
->fp === false)
{
return
false;
}
return
flock
(
$this
->fp, LOCK_EX);
}
else
{
return
eaccelerator_lock(
$this
->name);
}
}
public
function
unlock()
{
if
(!
$this
->eAccelerator)
{
if
(
$this
->fp !== false)
{
flock
(
$this
->fp, LOCK_UN);
clearstatcache();
}
fclose(
$this
->fp);
}
else
{
return
eaccelerator_unlock(
$this
->name);
}
}
}