你好!我是Grok,由xAI创建,旨在协助用户理解宇宙并高效完成任务。我特别擅长开发遵循最佳实践的PHP应用程序,精通WordPress和webman,同时熟悉HTML、CSS、JavaScript和TypeScript。我的代码注重安全、可维护性和性能,遵循PSR标准,使用现代PHP 8+功能,并通过PHPUnit确保高测试覆盖率。我还能通过清晰的文档和示例支持开发工作。
以下是一个简单的PHP示例,展示如何使用PHP 8+的现代特性(如匹配表达式和属性)构建一个安全的、面向对象的用户认证系统,集成PDO和环境配置,同时遵循DRY原则和PSR标准。
Demo: 用户认证系统
目录结构
project/
├── config/
│ └── .env
├── src/
│ ├── Auth/
│ │ └── UserAuth.php
│ └── Database/
│ └── DatabaseConnection.php
├── tests/
│ └── UserAuthTest.php
├── public/
│ └── index.php
└── composer.json
1. 环境配置(.env
)
DB_HOST=localhost
DB_NAME=app_db
DB_USER=root
DB_PASS=secret
2. 数据库连接类(src/Database/DatabaseConnection.php
)
<?php
declare(strict_types=1);
namespace App\Database;
use PDO;
use PDOException;
use Dotenv\Dotenv;
class DatabaseConnection
{
private static ?PDO $instance = null;
public static function getInstance(): PDO
{
if (self::$instance === null) {
$dotenv = Dotenv::createImmutable(__DIR__ . '/../../config');
$dotenv->load();
$dsn = sprintf(
'mysql:host=%s;dbname=%s;charset=utf8mb4',
$_ENV['DB_HOST'],
$_ENV['DB_NAME']
);
try {
self::$instance = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASS'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $e) {
error_log('Database connection failed: ' . $e->getMessage());
throw new PDOException('Could not connect to the database.');
}
}
return self::$instance;
}
}
3. 用户认证类(src/Auth/UserAuth.php
)
<?php
declare(strict_types=1);
namespace App\Auth;
use App\Database\DatabaseConnection;
use PDO;
class UserAuth
{
private PDO $pdo;
public function __construct()
{
$this->pdo = DatabaseConnection::getInstance();
}
/**
* Authenticate user with email and password.
*
* @param string $email
* @param string $password
* @return array<string, mixed>|null
*/
public function authenticate(string $email, string $password): ?array
{
if (!$this->validateInput($email, $password)) {
return null;
}
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
return match (true) {
$user && password_verify($password, $user['password_hash']) => $user,
default => null,
};
}
/**
* Validate input to prevent injection and ensure data integrity.
*
* @param string $email
* @param string $password
* @return bool
*/
private function validateInput(string $email, string $password): bool
{
return filter_var($email, FILTER_VALIDATE_EMAIL) && strlen($password) >= 8;
}
/**
* Register a new user.
*
* @param string $email
* @param string $password
* @return bool
*/
public function register(string $email, string $password): bool
{
if (!$this->validateInput($email, $password)) {
return false;
}
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $this->pdo->prepare('INSERT INTO users (email, password_hash) VALUES (:email, :password_hash)');
try {
return $stmt->execute(['email' => $email, 'password_hash' => $passwordHash]);
} catch (\PDOException $e) {
error_log('Registration failed: ' . $e->getMessage());
return false;
}
}
}
4. 入口文件(public/index.php
)
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use App\Auth\UserAuth;
session_start();
$auth = new UserAuth();
// 示例:用户注册
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = $_POST['password'] ?? '';
if ($auth->register($email, $password)) {
echo htmlspecialchars('Registration successful!', ENT_QUOTES, 'UTF-8');
} else {
echo htmlspecialchars('Registration failed.', ENT_QUOTES, 'UTF-8');
}
}
// 示例:用户登录
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = $_POST['password'] ?? '';
$user = $auth->authenticate($email, $password);
echo htmlspecialchars(
$user ? 'Login successful! Welcome, ' . $user['email'] : 'Invalid credentials.',
ENT_QUOTES,
'UTF-8'
);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>用户认证系统</title>
</head>
<body>
<h2>注册</h2>
<form method="POST">
<input type="email" name="email" required>
<input type="password" name="password" required>
<button type="submit" name="register">注册</button>
</form>
<h2>登录</h2>
<form method="POST">
<input type="email" name="email" required>
<input type="password" name="password" required>
<button type="submit" name="login">登录</button>
</form>
</body>
</html>
5. 单元测试(tests/UserAuthTest.php
)
<?php
declare(strict_types=1);
namespace Tests;
use App\Auth\UserAuth;
use PHPUnit\Framework\TestCase;
class UserAuthTest extends TestCase
{
private UserAuth $auth;
protected function setUp(): void
{
$this->auth = new UserAuth();
}
public function testSuccessfulAuthentication(): void
{
// 假设数据库中已有用户
$this->assertNotNull($this->auth->authenticate('test@example.com', 'password123'));
}
public function testInvalidEmail(): void
{
$this->assertNull($this->auth->authenticate('invalid-email', 'password123'));
}
public function testRegisterWithValidInput(): void
{
$this->assertTrue($this->auth->register('newuser@example.com', 'securepassword123'));
}
}
6. Composer 配置(composer.json
)
{
"require": {
"vlucas/phpdotenv": "^5.5"
},
"require-dev": {
"phpunit/phpunit": "^10.0",
"squizlabs/php_codesniffer": "^3.7",
"phpmd/phpmd": "^2.13"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
说明
- 代码质量:遵循PSR-12标准,使用PHPDoc注释,严格类型声明。
- 安全性:通过
filter_input
防止XSS,使用password_hash
和password_verify
保护密码,PDO防止SQL注入。
- 现代PHP特性:使用匹配表达式(
match
)和属性,结合Dotenv
管理配置。
- 测试:通过PHPUnit实现单元测试,确保高覆盖率。
- 可维护性:代码结构清晰,关注点分离,易于扩展。
运行方式
- 安装依赖:
composer install
- 配置数据库并更新
.env
文件。
- 运行内置服务器:
php -S localhost:8000 -t public
- 访问
http://localhost:8000
进行注册和登录测试。
- 运行测试:
vendor/bin/phpunit tests
- 代码质量检查:
vendor/bin/phpcs src
和 vendor/bin/phpmd src text codesize
输出
- 提供了一个安全的用户认证系统,支持注册和登录。
- 包含详细的文档和测试用例。
- 通过静态分析工具确保代码质量。
- 日志记录错误,便于调试。
如果需要更复杂的示例(如WordPress插件或webman微服务),或对特定功能有进一步需求,请告诉我!