在这个案例中,我们将使用PHP和MongoDB进行集成测试。我们将创建一个简单的用户注册和登录系统,包括用户数据的增删改查操作。
首先,确保已经安装了以下软件:
接下来,我们需要安装MongoDB的PHP扩展。在命令行中运行以下命令:
composer require mongodb/mongodb
现在我们可以开始编写代码了。首先,创建一个名为UserRepository.php
的文件,用于处理用户数据的增删改查操作:
<?php
require 'vendor/autoload.php';
use MongoDB\Client as Mongo;
class UserRepository
{
private $collection;
public function __construct()
{
$mongo = new Mongo("mongodb://localhost:27017");
$db = $mongo->selectDatabase("user_database");
$this->collection = $db->selectCollection("users");
}
public function createUser($username, $password)
{
$user = [
"username" => $username,
"password" => password_hash($password, PASSWORD_BCRYPT),
];
$result = $this->collection->insertOne($user);
return $result->getInsertedId();
}
public function getUserByUsername($username)
{
return $this->collection->findOne(["username" => $username]);
}
public function updateUser($userId, $data)
{
$result = $this->collection->updateOne(
["_id" => new \MongoDB\BSON\ObjectId($userId)],
['$set' => $data]
);
return $result->getModifiedCount();
}
public function deleteUser($userId)
{
$result = $this->collection->deleteOne(["_id" => new \MongoDB\BSON\ObjectId($userId)]);
return $result->getDeletedCount();
}
}
接下来,创建一个名为UserController.php
的文件,用于处理用户注册和登录的逻辑:
<?php
require 'UserRepository.php';
class UserController
{
private $userRepository;
public function __construct()
{
$this->userRepository = new UserRepository();
}
public function register($username, $password)
{
if ($this->userRepository->getUserByUsername($username)) {
throw new Exception("Username already exists.");
}
$userId = $this->userRepository->createUser($username, $password);
return $userId;
}
public function login($username, $password)
{
$user = $this->userRepository->getUserByUsername($username);
if (!$user || !password_verify($password, $user["password"])) {
throw new Exception("Invalid username or password.");
}
return $user;
}
}
最后,创建一个名为index.php
的文件,用于测试注册和登录功能:
<?php
require 'UserController.php';
$userController = new UserController();
// 注册
$userId = $userController->register("testuser", "testpassword");
echo "User registered with ID: " . $userId . "\n";
// 登录
$user = $userController->login("testuser", "testpassword");
echo "User logged in with ID: " . $user["_id"] . "\n";
现在,运行index.php
文件以测试注册和登录功能:
php index.php
如果一切正常,你应该会看到类似以下的输出:
User registered with ID: 60a8d4a15c1e000011004491
User logged in with ID: 60a8d4a15c1e000011004491
这个简单的案例展示了如何在PHP和MongoDB之间进行集成测试。你可以根据自己的需求对其进行扩展和优化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。