Home php教程 PHP源码 php支持apc和文件缓存的缓存类

php支持apc和文件缓存的缓存类

May 25, 2016 pm 05:04 PM

代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

<?php

class CacheException extends Exception {

}

 

/**

 * 缓存抽象类

 */

abstract class Cache_Abstract {

    /**

     * 读缓存变量

     *

     * @param string $key 缓存下标

     * @return mixed

     */

    abstract public function fetch($key);

 

    /**

     * 缓存变量

     *

     * @param string $key 缓存变量下标

     * @param string $value 缓存变量的值

     * @return bool

     */

    abstract public function store($key, $value);

 

    /**

     * 删除缓存变量

     *

     * @param string $key 缓存下标

     * @return Cache_Abstract

     */

    abstract public function delete($key);

 

    /**

     * 清(删)除所有缓存

     *

     * @return Cache_Abstract

     */

    abstract public function clear();

 

    /**

     * 锁定缓存变量

     *

     * @param string $key 缓存下标

     * @return Cache_Abstract

     */

    abstract public function lock($key);

 

    /**

     * 缓存变量解锁

     *

     * @param string $key 缓存下标

     * @return Cache_Abstract

     */

    abstract public function unlock($key);

 

    /**

     * 取得缓存变量是否被锁定

     *

     * @param string $key 缓存下标

     * @return bool

     */

    abstract public function isLocked($key);

 

    /**

     * 确保不是锁定状态

     * 最多做$tries次睡眠等待解锁,超时则跳过并解锁

     *

     * @param string $key 缓存下标

     */

    public function checkLock($key) {

        if (!$this -> isLocked($key)) {

            return $this;

        }

 

        $tries = 10;

        $count = 0;

        do {

            usleep(200);

            $count++;

        } while ($count <= $tries && $this->isLocked($key));// 最多做十次睡眠等待解锁,超时则跳过并解锁

 

        $this -> isLocked($key) && $this -> unlock($key);

 

        return $this;

    }

 

}

 

/**

 * APC扩展缓存实现

 *

 *

 * @category   Mjie

 * @package    Cache

 * @author     流水孟春

 * @copyright  Copyright (c) 2008- <cmpan(at)qq.com>

 * @license    New BSD License

 * @version    $Id: Cache/Apc.php 版本号 2010-04-18 23:02 cmpan $

 */

class Cache_Apc extends Cache_Abstract {

 

    protected $_prefix = &#39;cache.mjie.net&#39;;

 

    public function __construct() {

        if (!function_exists(&#39;apc_cache_info&#39;)) {

            throw new CacheException(&#39;apc extension didn&#39;t installed&#39;);

        }

    }

 

    /**

     * 保存缓存变量

     *

     * @param string $key

     * @param mixed $value

     * @return bool

     */

    public function store($key, $value) {

        return apc_store($this -> _storageKey($key), $value);

    }

 

    /**

     * 读取缓存

     *

     * @param string $key

     * @return mixed

     */

    public function fetch($key) {

        return apc_fetch($this -> _storageKey($key));

    }

 

    /**

     * 清除缓存

     *

     * @return Cache_Apc

     */

    public function clear() {

        apc_clear_cache();

        return $this;

    }

 

    /**

     * 删除缓存单元

     *

     * @return Cache_Apc

     */

    public function delete($key) {

        apc_delete($this -> _storageKey($key));

        return $this;

    }

 

    /**

     * 缓存单元是否被锁定

     *

     * @param string $key

     * @return bool

     */

    public function isLocked($key) {

        if ((apc_fetch($this -> _storageKey($key) . &#39;.lock&#39;)) === false) {

            return false;

        }

 

        return true;

    }

 

    /**

     * 锁定缓存单元

     *

     * @param string $key

     * @return Cache_Apc

     */

    public function lock($key) {

        apc_store($this -> _storageKey($key) . &#39;.lock&#39;, &#39;&#39;, 5);

        return $this;

    }

 

    /**

     * 缓存单元解锁

     *

     * @param string $key

     * @return Cache_Apc

     */

    public function unlock($key) {

        apc_delete($this -> _storageKey($key) . &#39;.lock&#39;);

        return $this;

    }

 

    /**

     * 完整缓存名

     *

     * @param string $key

     * @return string

     */

    private function _storageKey($key) {

        return $this -> _prefix . &#39;_&#39; . $key;

    }

 

}

 

/**

 * 文件缓存实现

 *

 *

 * @category   Mjie

 * @package    Cache

 * @author     流水孟春

 * @copyright  Copyright (c) 2008- <cmpan(at)qq.com>

 * @license    New BSD License

 * @version    $Id: Cache/File.php 版本号 2010-04-18 16:46 cmpan $

 */

class Cache_File extends Cache_Abstract {

    public $useSubdir = false;

 

    protected $_cachesDir = &#39;cache&#39;;

 

    public function __construct() {

        if (defined(&#39;DATA_DIR&#39;)) {

            $this -> _setCacheDir(DATA_DIR . &#39;/cache&#39;);

        }

    }

 

    /**

     * 获取缓存文件

     *

     * @param string $key

     * @return string

     */

    protected function _getCacheFile($key) {

        $subdir = $this -> useSubdir ? substr($key, 0, 2) . &#39;/&#39; : &#39;&#39;;

        return $this -> _cachesDir . &#39;/&#39; . $subdir . $key . &#39;.php&#39;;

    }

 

    /**

     * 读取缓存变量

     * 为防止信息泄露,缓存文件格式为php文件,并以"<?php exit;?>"开头

     *

     * @param string $key 缓存下标

     * @return mixed

     */

    public function fetch($key) {

        $cacheFile = self::_getCacheFile($key);

        if (file_exists($cacheFile) && is_readable($cacheFile)) {

            // include 方式

            //return include $cacheFile;

            // 系列化方式

 

            return unserialize(@file_get_contents($cacheFile, false, NULL, 13));

        }

 

        return false;

    }

 

    /**

     * 缓存变量

     * 为防止信息泄露,缓存文件格式为php文件,并以"<?php exit;?>"开头

     *

     * @param string $key 缓存变量下标

     * @param string $value 缓存变量的值

     * @return bool

     */

    public function store($key, $value) {

        $cacheFile = self::_getCacheFile($key);

        $cacheDir = dirname($cacheFile);

 

        if (!is_dir($cacheDir)) {

            if (!@mkdir($cacheDir, 0755, true)) {

                throw new CacheException("Could not make cache directory");

            }

        }

        // 用include方式

        //return @file_put_contents($cacheFile, &#39;<?php return &#39; . var_export($value, true). &#39;;&#39;);

 

        return @file_put_contents($cacheFile, &#39;<?php exit;?>&#39; . serialize($value));

    }

 

    /**

     * 删除缓存变量

     *

     * @param string $key 缓存下标

     * @return Cache_File

     */

    public function delete($key) {

        if (emptyempty($key)) {

            throw new CacheException("Missing argument 1 for Cache_File::delete()");

        }

 

        $cacheFile = self::_getCacheFile($key);

        if (!@unlink($cacheFile)) {

            throw new CacheException("Cache file could not be deleted");

        }

 

        return $this;

    }

 

    /**

     * 缓存单元是否已经锁定

     *

     * @param string $key

     * @return bool

     */

    public function isLocked($key) {

        $cacheFile = self::_getCacheFile($key);

        clearstatcache();

        return file_exists($cacheFile . &#39;.lock&#39;);

    }

 

    /**

     * 锁定

     *

     * @param string $key

     * @return Cache_File

     */

    public function lock($key) {

        $cacheFile = self::_getCacheFile($key);

        $cacheDir = dirname($cacheFile);

        if (!is_dir($cacheDir)) {

            if (!@mkdir($cacheDir, 0755, true)) {

                if (!is_dir($cacheDir)) {

                    throw new CacheException("Could not make cache directory");

                }

            }

        }

 

        // 设定缓存锁文件的访问和修改时间

        @touch($cacheFile . &#39;.lock&#39;);

        return $this;

    }

 

    /**

     * 解锁

     *

     * @param string $key

     * @return Cache_File

     */

    public function unlock($key) {

        $cacheFile = self::_getCacheFile($key);

        @unlink($cacheFile . &#39;.lock&#39;);

        return $this;

    }

 

    /**

     * 设置文件缓存目录

     * @param string $dir

     * @return Cache_File

     */

    protected function _setCacheDir($dir) {

        $this -> _cachesDir = rtrim(str_replace(&#39;\&#39;, &#39;/&#39;, trim($dir)), &#39;/&#39;);

        clearstatcache();

        if (!is_dir($this -> _cachesDir)) {

            mkdir($this -> _cachesDir, 0755, true);

        }

        //

        return $this;

    }

 

    /**

     * 清空所有缓存

     *

     * @return Cache_File

     */

    public function clear() {

        // 遍历目录清除缓存

        $cacheDir = $this -> _cachesDir;

        $d = dir($cacheDir);

        while (false !== ($entry = $d -> read())) {

            if (&#39;.&#39; == $entry[0]) {

                continue;

            }

 

            $cacheEntry = $cacheDir . &#39;/&#39; . $entry;

            if (is_file($cacheEntry)) {

                @unlink($cacheEntry);

            } elseif (is_dir($cacheEntry)) {

                // 缓存文件夹有两级

                $d2 = dir($cacheEntry);

                while (false !== ($entry = $d2 -> read())) {

                    if (&#39;.&#39; == $entry[0]) {

                        continue;

                    }

 

                    $cacheEntry .= &#39;/&#39; . $entry;

                    if (is_file($cacheEntry)) {

                        @unlink($cacheEntry);

                    }

                }

                $d2 -> close();

            }

        }

        $d -> close();

 

        return $this;

    }

 

}

 

/**

 * 缓存单元的数据结构

 * array(

 *         &#39;time&#39; => time(),     // 缓存写入时的时间戳

 *         &#39;expire&#39; => $expire, // 缓存过期时间

 *         &#39;valid&#39; => true,         // 缓存是否有效

 *         &#39;data&#39; => $value         // 缓存的值

 * );

 */

final class Cache {

    /**

     * 缓存过期时间长度(s)

     *

     * @var int

     */

    private $_expire = 3600;

    /**

     * 缓存处理类

     *

     * @var Cache_Abstract

     */

    private $_storage = null;

    /**

     * @return Cache

     */

    static public function createCache($cacheClass = &#39;Cache_File&#39;) {

        return new self($cacheClass);

    }

 

    private function __construct($cacheClass) {

        $this -> _storage = new $cacheClass();

    }

 

    /**

     * 设置缓存

     *

     * @param string $key

     * @param mixed $value

     * @param int $expire

     */

    public function set($key, $value, $expire = false) {

        if (!$expire) {

            $expire = $this -> _expire;

        }

 

        $this -> _storage -> checkLock($key);

 

        $data = array(&#39;time&#39; => time(), &#39;expire&#39; => $expire, &#39;valid&#39; => true, &#39;data&#39; => $value);

        $this -> _storage -> lock($key);

 

        try {

            $this -> _storage -> store($key, $data);

            $this -> _storage -> unlock($key);

        } catch (CacheException $e) {

            $this -> _storage -> unlock($key);

            throw $e;

        }

    }

 

    /**

     * 读取缓存

     *

     * @param string $key

     * @return mixed

     */

    public function get($key) {

        $data = $this -> fetch($key);

        if ($data && $data[&#39;valid&#39;] && !$data[&#39;isExpired&#39;]) {

            return $data[&#39;data&#39;];

        }

 

        return false;

    }

 

    /**

     * 读缓存,包括过期的和无效的,取得完整的存贮结构

     *

     * @param string $key

     */

    public function fetch($key) {

        $this -> _storage -> checkLock($key);

        $data = $this -> _storage -> fetch($key);

        if ($data) {

            $data[&#39;isExpired&#39;] = (time() - $data[&#39;time&#39;]) > $data[&#39;expire&#39;] ? true : false;

            return $data;

        }

 

        return false;

    }

 

    /**

     * 删除缓存

     *

     * @param string $key

     */

    public function delete($key) {

        $this -> _storage -> checkLock($key) -> lock($key) -> delete($key) -> unlock($key);

    }

 

    public function clear() {

        $this -> _storage -> clear();

    }

 

    /**

     * 把缓存设为无效

     *

     * @param string $key

     */

    public function setInvalidate($key) {

        $this -> _storage -> checkLock($key) -> lock($key);

        try {

            $data = $this -> _storage -> fetch($key);

            if ($data) {

                $data[&#39;valid&#39;] = false;

                $this -> _storage -> store($key, $data);

            }

            $this -> _storage -> unlock($key);

        } catch (CacheException $e) {

            $this -> _storage -> unlock($key);

            throw $e;

        }

    }

 

    /**

     * 设置缓存过期时间(s)

     *

     * @param int $expire

     */

    public function setExpire($expire) {

        $this -> _expire = (int)$expire;

        return $this;

    }

 

}

Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)