admin 发表于 2026-5-30 15:53:37

thinkphp6 真实业务场景:接口实战(缓存接口 + 日志接口)

企业级最常用、最标准、能直接放进你项目里的代码,让你彻底理解:
一个类实现多个接口在 TP6 里到底怎么用。
一、先定义两个接口(制定规矩):
1. 日志接口(app/library/LogInterface.php):

<?php
namespace app\library;

// 日志接口:规定必须有写日志的方法
interface LogInterface
{
    // 规定:必须实现写日志方法
    public function writeLog(string $content): void;
}2. 缓存接口(app/library/CacheInterface.php):

<?php
namespace app\library;

// 缓存接口:规定必须有设置、获取缓存的方法
interface CacheInterface
{
    public function setCache(string $key, $value, int $expire = 3600): bool;
    public function getCache(string $key);
}二、写一个用户类,同时实现这两个接口:

文件:app/library/UserService.php:

<?php
namespace app\library;

// 重点:一个类 implement 多个接口,用逗号分隔
class UserService implements LogInterface, CacheInterface
{
    // ========================
    // 必须实现:LogInterface 的方法
    // ========================
    public function writeLog(string $content): void
    {
      // 真实写日志逻辑
      file_put_contents('./log.txt', date('Y-m-d H:i:s') . ' ' . $content . PHP_EOL, FILE_APPEND);
    }

    // ========================
    // 必须实现:CacheInterface 的方法
    // ========================
    public function setCache(string $key, $value, int $expire = 3600): bool
    {
      return cache($key, $value, $expire);
    }

    public function getCache(string $key)
    {
      return cache($key);
    }

    // ========================
    // 自己的业务方法
    // ========================
    public function getUserInfo(int $userId)
    {
      // 用缓存
      $key = "user:$userId";
      $user = $this->getCache($key);

      if (!$user) {
            $user = ['id' => $userId, 'name' => '测试用户'];
            $this->setCache($key, $user);
            // 用日志
            $this->writeLog("用户ID:$userId 缓存不存在,已重新设置");
      }

      return $user;
    }
}三、控制器里调用(最真实用法):

文件:app/controller/User.php:

<?php
namespace app\controller;

use app\library\UserService;

class User
{
    public function index()
    {
      $service = new UserService();

      // 调用业务方法
      $user = $service->getUserInfo(100);

      // 直接调用接口方法也可以
      $service->writeLog('用户访问了首页');

      return json($user);
    }
}四、你马上能看懂的关键点:

一个类实现多个接口的写法:

class UserService implements LogInterface, CacheInterface逗号分隔,想加几个接口就加几个。
2. 必须实现所有接口里的所有方法
实现 LogInterface → 必须写 writeLog()
实现 CacheInterface → 必须写 setCache() + getCache()
少一个都会直接报错,这就是接口的作用:强制规范。
3. 接口好处(实战价值)
统一代码规范
团队协作不混乱
方便以后切换驱动(比如换成 Redis 缓存)五、一句话总结这个例子:
UserService 既是一个日志工具,也是一个缓存工具,同时还是用户业务类。
页: [1]
查看完整版本: thinkphp6 真实业务场景:接口实战(缓存接口 + 日志接口)