news 2026/6/8 18:39:10

PHP接口设计与抽象类应用

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
PHP接口设计与抽象类应用

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('数据库错误');
?>

接口定义了能做什么,抽象类定义了是什么。接口可以多实现,抽象类只能单继承。在实际项目中,接口用于定义契约,抽象类用于代码复用。两者结合使用可以构建灵活的设计。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/8 18:34:47

PHP内存管理与垃圾回收机制

PHP内存管理与垃圾回收机制PHP的内存管理对开发者几乎是透明的,但了解底层机制有助于写出更高效的代码。今天说说PHP的内存管理和垃圾回收。PHP使用引用计数来管理内存。每个变量底层是一个zval结构体,里面有个refcount字段记录有多少个变量指向它。php$…

作者头像 李华
网站建设 2026/6/8 18:34:46

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 想要在…

作者头像 李华
网站建设 2026/6/8 18:33:55

SAP与WMS集成实战:当发货单要撤回时,我是如何用VL09 BDC + BAPI_OUTB_DELIVERY_CHANGE搞定取消过账和批次拆分还原的

SAP与WMS集成中的发货单撤回实战:VL09 BDC与BAPI_OUTB_DELIVERY_CHANGE的完美组合在SAP与WMS系统集成的复杂环境中,发货单的撤回操作往往成为最棘手的业务场景之一。想象一下这样的情景:仓库管理系统已经完成了发货过账,突然接到客…

作者头像 李华