PHP常用的类封装小结【4个工具类】
在PHP开发中,使用类的封装可以提高代码的复用性、可维护性和可读性。本文介绍了4种常用的PHP类封装,包括:
- Curl类封装
- Redis类封装
- MySQL类封装
- 日志类封装
下面将详细介绍这4种类的封装方法以及使用场景。
Curl类封装
Curl是一种网络传输工具,PHP中内置了Curl扩展,可以用来发送HTTP请求等。封装Curl类可以减少重复代码,方便使用。以下是Curl类封装的示例代码:
class Curl
{
public static function get($url, $params = [], $headers = [])
{
// 初始化
$ch = curl_init();
// 设置URL和其他参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (!empty($params)) {
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
}
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
// 执行
$response = curl_exec($ch);
// 关闭
curl_close($ch);
return $response;
}
public static function post($url, $params = [], $headers = [])
{
// 初始化
$ch = curl_init();
// 设置URL和其他参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
// 执行
$response = curl_exec($ch);
// 关闭
curl_close($ch);
return $response;
}
}
使用示例:
$result = Curl::get('https://www.example.com/api', ['page' => 1], ['Authorization: Bearer token']);
echo $result;
$result = Curl::post('https://www.example.com/api', ['username' => 'admin', 'password' => '123456'], ['Authorization: Bearer token']);
echo $result;
Redis类封装
Redis是一种内存数据库,常用于缓存数据等。使用Redis类封装可以方便地连接和操作Redis。以下是Redis类封装的示例代码:
class RedisClient
{
private $redis;
public function __construct($host, $port, $password = null, $database = 0)
{
$this->redis = new Redis();
$this->redis->connect($host, $port);
if (!empty($password)) {
$this->redis->auth($password);
}
$this->redis->select($database);
}
public function set($key, $value, $expire = 0)
{
$this->redis->set($key, $value);
if ($expire > 0) {
$this->redis->expire($key, $expire);
}
}
public function get($key)
{
return $this->redis->get($key);
}
public function delete($key)
{
return $this->redis->del($key);
}
}
使用示例:
$redis = new RedisClient('127.0.0.1', 6379, 'password', 0);
$redis->set('name', 'John', 3600);
$name = $redis->get('name');
echo $name;
$redis->delete('name');
MySQL类封装
MySQL是一种关系型数据库,使用MySQL类封装可以方便地连接和操作MySQL。以下是MySQL类封装的示例代码:
class MySQLClient
{
private $mysqli;
public function __construct($host, $username, $password, $database, $port = 3306)
{
$this->mysqli = new mysqli($host, $username, $password, $database, $port);
if ($this->mysqli->connect_error) {
throw new Exception($this->mysqli->connect_error);
}
$this->mysqli->set_charset('utf8mb4');
}
public function query($sql)
{
$result = $this->mysqli->query($sql);
if ($result === false) {
throw new Exception($this->mysqli->error);
}
return $result;
}
public function execute($sql)
{
$result = $this->mysqli->query($sql);
if ($result === false) {
throw new Exception($this->mysqli->error);
}
return $this->mysqli->affected_rows;
}
public function fetchAll($sql)
{
$result = $this->mysqli->query($sql);
if ($result === false) {
throw new Exception($this->mysqli->error);
}
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
}
使用示例:
$mysql = new MySQLClient('localhost', 'root', 'password', 'test', 3306);
$result = $mysql->fetchAll('SELECT * FROM users WHERE age > 18');
print_r($result);
$count = $mysql->execute('UPDATE users SET status = 1 WHERE age > 18');
echo $count;
日志类封装
日志记录是一种常见的需求,在PHP开发中经常需要记录各种信息以便于排查问题。使用日志类封装可以方便地记录和管理日志。以下是日志类封装的示例代码:
class Logger
{
private $file;
public function __construct($file)
{
$this->file = $file;
}
public function log($level, $message, $context = [])
{
$dateTime = (new DateTime())->format('Y-m-d H:i:s');
$contextString = '';
if (!empty($context)) {
$contextString = json_encode($context, JSON_UNESCAPED_UNICODE);
}
$line = sprintf('[%s] [%s] %s %s%s', $dateTime, $level, $message, $contextString, PHP_EOL);
file_put_contents($this->file, $line, FILE_APPEND);
}
public function debug($message, $context = [])
{
$this->log('DEBUG', $message, $context);
}
public function info($message, $context = [])
{
$this->log('INFO', $message, $context);
}
public function warning($message, $context = [])
{
$this->log('WARNING', $message, $context);
}
public function error($message, $context = [])
{
$this->log('ERROR', $message, $context);
}
}
使用示例:
$logger = new Logger('app.log');
$logger->info('User login', ['username' => 'admin']);
$logger->warning('Invalid request', ['ip' => '127.0.0.1']);
以上是4种常用的PHP类封装方法的详细介绍和示例。这些类的封装都可以提高代码的复用性、可维护性和可读性,在使用中可以根据实际情况进行调整和拓展。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:PHP常用的类封装小结【4个工具类】 - Python技术站