二次开发

本文介绍如何对 YXShop 进行二次开发,包括新增模块和扩展现有功能。

新增后端模块

以新增「文章管理」模块为例,按四层架构创建:

1. 创建 Model

php
class Article extends BaseModel
{
    protected $table = 'article';
    protected $fillable = ['title', 'content', 'status'];

    public function category(): BelongsTo
    {
        return $this->belongsTo(ArticleCategory::class, 'category_id');
    }
}

2. 创建 Repository

php
class ArticleRepository extends BaseRepository
{
    public function __construct(Article $model)
    {
        parent::__construct($model);
    }
}

3. 创建 Service

php
class ArticleService
{
    public function __construct(
        private readonly ArticleRepository $articleRepo
    ) {}

    public function getList(array $params): array
    {
        return $this->articleRepo->paginate($params);
    }

    public function create(array $data): Article
    {
        return $this->articleRepo->create($data);
    }
}

4. 创建 Controller 并注册路由

php
// config/route/admin_api.php
$router->get('/articles', [ArticleController::class, 'list']);
$router->post('/articles', [ArticleController::class, 'create']);