PHP接口设计与抽象类应用
接口和抽象类是面向对象设计的重要工具。接口定义契约,抽象类提供基础实现。今天说说它们的区别和使用场景。
接口声明了类必须实现的方法。
```php
interface CacheInterface
{
public function get(string $key): mixed;
public function set(string $key, mixed $value, int $ttl = 3600): void;
public function delete(string $key): bool;
public function clear(): void;
}
class RedisCache implements CacheInterface
{
private Redis $redis;
public function __construct()
{
$this->redis = new Redis();
$this->redis->connect('127.0.0.1', 6379);
}
public function get(string $key): mixed
{
$value = $this->redis->get($key);
return $value !== false ? unserialize($value) : null;
}
public function set(string $key, mixed $value, int $ttl = 3600): void
{
$this->redis->setex($key, $ttl, serialize($value));
}
public function delete(string $key): bool
{
return $this->redis->del($key) > 0;
}
public function clear(): void
{
$keys = $this->redis->keys('*');
if (!empty($keys)) $this->redis->del($keys);
}
}
class FileCache implements CacheInterface
{
private string $dir;
public function __construct(string $dir = '/tmp/cache')
{
$this->dir = rtrim($dir, '/');
if (!is_dir($this->dir)) mkdir($this->dir, 0755, true);
}
public function get(string $key): mixed
{
$path = $this->getPath($key);
if (!file_exists($path)) return null;
if (time() - filemtime($path) > 3600) {
unlink($path);
return null;
}
return unserialize(file_get_contents($path));
}
public function set(string $key, mixed $value, int $ttl = 3600): void
{
file_put_contents($this->getPath($key), serialize($value));
}
public function delete(string $key): bool
{
$path = $this->getPath($key);
if (file_exists($path)) return unlink($path);
return false;
}
public function clear(): void
{
array_map('unlink', glob($this->dir . '/*'));
}
private function getPath(string $key): string
{
return $this->dir . '/' . md5($key) . '.cache';
}
}
$cache = new RedisCache();
$cache->set('test', ['name' => '张三']);
echo $cache->get('test')['name'] . "\n";
?>
抽象类可以包含已实现的方法和抽象方法。
```php
abstract class AbstractLogger
{
protected string $format = "[{time}] {level}: {message}\n";
abstract protected function write(string $line): void;
public function info(string $message): void
{
$this->log('INFO', $message);
}
public function error(string $message): void
{
$this->log('ERROR', $message);
}
private function log(string $level, string $message): void
{
$line = str_replace(
['{time}', '{level}', '{message}'],
[date('Y-m-d H:i:s'), $level, $message],
$this->format
);
$this->write($line);
}
}
class FileLogger extends AbstractLogger
{
private string $path;
public function __construct(string $path = '/tmp/app.log')
{
$this->path = $path;
}
protected function write(string $line): void
{
file_put_contents($this->path, $line, FILE_APPEND | LOCK_EX);
}
}
class EchoLogger extends AbstractLogger
{
protected function write(string $line): void
{
echo $line;
}
}
$logger = new FileLogger();
$logger->info('用户登录');
$logger->error('数据库错误');
?>
接口定义了能做什么,抽象类定义了是什么。接口可以多实现,抽象类只能单继承。在实际项目中,接口用于定义契约,抽象类用于代码复用。两者结合使用可以构建灵活的设计。
PHP接口设计与抽象类应用
张小明
前端开发工程师
告别课程论文焦虑!paperxie 智能写作,把你的期末 “难题” 变成加分项
paperxie-免费查重复率aigc检测/开题报告/毕业论文/智能排版/文献综述/课程论文课程论文 - PaperXie智能写作PaperXieAi论文智能生成软件,10分钟生成万字毕业论文、期刊论文、文献综述、PPT,Aigc查重、降重报告、文献资料。只需一个标题,从开…
如何用WeChatMsg构建你的个人数字记忆库:从聊天记录到AI训练数据的终极指南
如何用WeChatMsg构建你的个人数字记忆库:从聊天记录到AI训练数据的终极指南 【免费下载链接】WeChatMsg 提取微信聊天记录,将其导出成HTML、Word、CSV文档永久保存,对聊天记录进行分析生成年度聊天报告 项目地址: https://gitcode.com/GitH…
PHP内存管理与垃圾回收机制
PHP内存管理与垃圾回收机制PHP的内存管理对开发者几乎是透明的,但了解底层机制有助于写出更高效的代码。今天说说PHP的内存管理和垃圾回收。PHP使用引用计数来管理内存。每个变量底层是一个zval结构体,里面有个refcount字段记录有多少个变量指向它。php$…
Joplin快捷键终极指南:200+效率操作完全解析
Joplin快捷键终极指南:200效率操作完全解析 【免费下载链接】joplin Joplin - the privacy-focused note taking app with sync capabilities for Windows, macOS, Linux, Android and iOS. 项目地址: https://gitcode.com/GitHub_Trending/jo/joplin 想要在…
YOLOv5训练全流程避坑指南:从数据增强(Mosaic/MixUp)到损失计算(CIoU)的实战细节
YOLOv5训练全流程避坑指南:从数据增强到损失计算的实战精要当你在深夜盯着屏幕,看着训练曲线像过山车一样起伏不定时,是否想过——那些隐藏在YOLOv5默认参数背后的设计哲学,才是决定模型成败的关键?本文将带你深入训练…
SAP与WMS集成实战:当发货单要撤回时,我是如何用VL09 BDC + BAPI_OUTB_DELIVERY_CHANGE搞定取消过账和批次拆分还原的
SAP与WMS集成中的发货单撤回实战:VL09 BDC与BAPI_OUTB_DELIVERY_CHANGE的完美组合在SAP与WMS系统集成的复杂环境中,发货单的撤回操作往往成为最棘手的业务场景之一。想象一下这样的情景:仓库管理系统已经完成了发货过账,突然接到客…