nextphp/data

NextPHP 数据包是 PHP 开发者的强大工具,提供 ORM 功能和直接 SQL 查询执行。该包是 NextPHP 框架的一部分,这是一个现代且轻量级的 PHP 框架,旨在提高性能和可扩展性。

1.3.0 2024-07-19 22:35 UTC

This package is auto-updated.

Last update: 2024-09-05 11:49:22 UTC


README

NextPHP Data 包是 PHP 开发者的强大工具,提供 ORM 功能和直接 SQL 查询执行。它通过允许开发人员使用对象而不是原始 SQL 查询来简化数据库交互。通过支持属性来定义实体和关系,NextPHP Data 确保代码库干净高效。

此包是 NextPHP 框架 的一部分,这是一个现代且轻量级的 PHP 框架,旨在提高性能和可扩展性。NextPHP 旨在提供一套全面的工具和库,以简化开发过程。

功能

  • 基于属性的 ORM 实体定义
  • 直接 SQL 查询功能
  • 事务支持
  • 关系处理(OneToMany, ManyToOne 等)
  • 易于与现有项目集成

安装

通过 Composer 安装

要安装 NextPHP 数据包,您需要使用 Composer 将其添加到您的项目中。

composer require nextphp/data

使用 NextPHP 数据的示例项目

这是一个示例项目,演示了 NextPHP 数据包的使用,包括 ORM 和直接 SQL 查询功能。

基本用法

定义实体

实体代表数据库中的表。使用属性定义属性及其类型。

用法

使用实体

<?php
namespace Example;

use NextPHP\Data\Persistence\Column;
use NextPHP\Data\Persistence\Entity;
use NextPHP\Data\Persistence\GeneratedValue;
use NextPHP\Data\Persistence\Id;
use NextPHP\Data\Persistence\Table;

#[Entity(name: "users")]
class User
{
    #[Id]
    #[Column('INT AUTO_INCREMENT PRIMARY KEY', false)]
    public int $id;

    #[Column('VARCHAR(255)', false)]
    public string $name;

    #[Column('VARCHAR(255)', false)]
    public string $email;

    #[Column('VARCHAR(255)', false)]
    public string $password;

    // getters and setters
}

高级实体用法

OneToMany 和 ManyToOne 关系使用属性定义。

<?php
namespace Example;

use NextPHP\Data\Persistence\Column;
use NextPHP\Data\Persistence\Entity;
use NextPHP\Data\Persistence\GeneratedValue;
use NextPHP\Data\Persistence\Id;
use NextPHP\Data\Persistence\Table;

#[Entity(name: "users")]
class Post
{
    #[Id]
    #[Column('INT AUTO_INCREMENT PRIMARY KEY', false)]
    public int $id;

    #[Column('VARCHAR(255)', false)]
    public string $title;

    #[Column('TEXT', false)]
    public string $content;

    #[Column('INT', false)]
    public int $user_id;

    // example for ManyToMany, OneToMany etc.
    #[ManyToOne(targetEntity: User::class, inversedBy: 'posts')]
    private User $user;

    // getters and setters
}

使用存储库

存储库处理实体的数据库操作。扩展 BaseRepository 并指定实体类。

<?php
namespace Example;

use NextPHP\Data\BaseRepository;

#[Repository(entityClass: User::class)]
class UserRepository extends BaseRepository
{
    // No need for constructor
}

服务层

服务提供业务逻辑并与存储库交互。

<?php
namespace Example;

#[Service(description: 'User management service')]
class UserService
{
    private UserRepository $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    #[Transactional]
    public function registerUser(array $userData): User
    {
        $user = new User();
        $user->name = $userData['name'];
        $user->email = $userData['email'];
        $user->password = password_hash($userData['password'], PASSWORD_DEFAULT);

        $userArray = [
            'name' => $user->name,
            'email' => $user->email,
            'password' => $user->password,
        ];

        $this->userRepository->save($userArray);

        return $user;
    }

    public function getAllUsers(): array
    {
        return $this->userRepository->findAll();
    }

    public function getUserById(int $id): ?User
    {
        $userArray = $this->userRepository->find($id);
        if (!$userArray) {
            return null;
        }

        $user = new User();
        $user->id = $userArray['id'];
        $user->name = $userArray['name'];
        $user->email = $userArray['email'];
        $user->password = $userArray['password'] ?? '';

        return $user;
    }

    public function updateUser(int $id, array $data): ?User
    {
        $user = $this->getUserById($id);
        if (!$user) {
            return null;
        }

        foreach ($data as $key => $value) {
            if (property_exists($user, $key)) {
                $user->$key = $value;
            }
        }

        $userArray = get_object_vars($user);
        $this->userRepository->update($id, $userArray);

        return $user;
    }

    public function deleteUser(int $id): bool
    {
        $user = $this->getUserById($id);
        if (!$user) {
            return false;
        }

        $this->userRepository->delete($id);

        return true;
    }
}

示例项目

项目结构示例

example/
├── src/
│   ├── Entity/User.php
│   ├── Repository/UserRepository.php
│   ├── Service/UserService.php
├── example.php
├── composer.json
└── README.md

测试

要测试 NextPHP 数据包,您可以创建一个 index.php 文件并使用服务层执行各种 CRUD 操作。以下是您可以这样做的示例

示例 index 或 example.php

<?php
require 'vendor/autoload.php';

use Example\UserService;
use Example\UserRepository;
use Example\PostService;
use Example\PostRepository;

// Initialize the repositories
$userRepository = new UserRepository();
$postRepository = new PostRepository();

// Initialize the services
$userService = new UserService($userRepository);
$postService = new PostService($postRepository);

// Example: Register a new user
$newUser = $userService->registerUser([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => 'secret',
]);

echo "New User Registered: " . $newUser->name . "\n";

// Example: Get all users
$users = $userService->getAllUsers();
echo "All Users:\n";
print_r($users);

// Example: Get a user by ID
$user = $userService->getUserById($newUser->id);
echo "User with ID {$newUser->id}:\n";
print_r($user);

// Example: Update a user
$updatedUser = $userService->updateUser($newUser->id, ['name' => 'Jane Doe']);
echo "Updated User: " . $updatedUser->name . "\n";

// Example: Delete a user
$isDeleted = $userService->deleteUser($newUser->id);
echo "User Deleted: " . ($isDeleted ? 'Yes' : 'No') . "\n";

// Example: Create a new post
$newPost = $postService->createPost([
    'title' => 'Hello World',
    'content' => 'This is my first post!',
    'user_id' => $newUser->id, // Assign the post to the new user
]);

echo "New Post Created: " . $newPost->title . "\n";

// Example: Get all posts
$posts = $postService->getAllPosts();
echo "All Posts:\n";
print_r($posts);

// Example: Get a post by ID
$post = $postService->getPostById($newPost->id);
echo "Post with ID {$newPost->id}:\n";
print_r($post);

// Example: Update a post
$updatedPost = $postService->updatePost($newPost->id, ['title' => 'Updated Title']);
echo "Updated Post: " . $updatedPost->title . "\n";

// Example: Delete a post
$isPostDeleted = $postService->deletePost($newPost->id);
echo "Post Deleted: " . ($isPostDeleted ? 'Yes' : 'No') . "\n";

贡献

我们欢迎贡献!以下是如何帮助的

  • 报告问题:发现错误?在 GitHub 上报告。
  • 建议功能:有想法?与我们分享。
  • 提交拉取请求:改进代码库。
  • 增强文档:帮助我们改进我们的文档。

有关更多详细信息,请参阅我们的 贡献指南

资源

加入我们的社区

  • Twitter:Twitter 上关注我们
  • Discord:加入我们的 Discord 社区。

联系我们

感谢您成为 NextPHP 社区的一员!




常见问题解答 (FAQ)

问:如何定义实体?

答:使用 #[Entity] 属性将类定义为实体,并使用 #[Entity(name: "table_name")] 或 #[Table(name: "table_name")] 属性来指定表名。

更多信息,请参阅我们的 常见问题解答 (FAQ)