您好,登錄后才能下訂單哦!
在這個案例中,我們將使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。