承接 nextphp/data 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

nextphp/data

Composer 安装命令:

composer require nextphp/data

包简介

The NextPHP Data package is a powerful tool for PHP developers, providing ORM capabilities and direct SQL query execution. This package is part of the NextPHP Framework, a modern and lightweight PHP framework designed for performance and scalability.

README 文档

README

The NextPHP Data package is a powerful tool for PHP developers, providing ORM capabilities and direct SQL query execution. It simplifies database interactions by allowing developers to work with objects instead of raw SQL queries. With support for attributes to define entities and relationships, NextPHP Data ensures a clean and efficient codebase.

This package is part of the NextPHP Framework, a modern and lightweight PHP framework designed for performance and scalability. NextPHP aims to provide a comprehensive suite of tools and libraries to streamline the development process.

Features

  • ORM with attribute-based entity definitions
  • Direct SQL query capabilities
  • Transactional support
  • Relationship handling (OneToMany, ManyToOne, etc.)
  • Easy integration with existing projects

Installation

Installing via Composer

To install the NextPHP Data package, you need to add it to your project using Composer.

composer require nextphp/data

Example Project using NextPHP Data

This is an example project demonstrating the usage of the NextPHP Data package, which includes ORM and direct SQL query capabilities.

Basic Usage

Defining Entities

Entities represent the tables in your database. Use attributes to define the properties and their types.

Usage

Using Entity

<?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
}

Advanced Entity Usage

Relationships OneToMany and ManyToOne Define relationships using attributes.

<?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
}

Using Repository

Repositories handle database operations for entities. Extend BaseRepository and specify the entity class.

<?php
namespace Example;

use NextPHP\Data\BaseRepository;

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

Service Layer

Services provide business logic and interact with repositories.

<?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 Project

Example for your Project Structure

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

Testing

To test the NextPHP Data package, you can create an index.php file and use the service layer to perform various CRUD operations. Here is an example of how you can do this:

Example index or 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";

Contributing

We welcome contributions! Here’s how you can help:

  • Report Issues: Found a bug? Report it on GitHub.
  • Suggest Features: Have an idea? Share it with us.
  • Submit Pull Requests: Improve the codebase.
  • Enhance Documentation: Help us improve our docs.

For more details, see our Contribution Guidelines.

Resources

Join Our Community

Contact Us

Thank you for being part of the NextPHP community!




FAQ

Q: How do I define an entity?

A: Use the #[Entity] attribute to define a class as an entity and the #[Entity(name: "table_name")] OR #[Table(name: "table_name")] attribute to specify the table name.

For more details, see our FAQ.

nextphp/data 适用场景与选型建议

nextphp/data 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 30 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 07 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「framework」 「database」 「orm」 「php」 「sql」 「nextphp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 nextphp/data 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 nextphp/data 我们能提供哪些服务?
定制开发 / 二次开发

基于 nextphp/data 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 30
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 28
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-07-03