当需要异步批量删除文章时,Controller 如何返回符合 Joomla API 规范的 JSON 响应?

解读

国内 Joomla 项目普遍前后端分离,管理后台大量采用 Vue/React 直调后端接口。面试官问“异步批量删除文章”,重点不在“删除”而在“如何按 Joomla 官方契约给出 JSON”。
现场评分维度:

  1. 是否走 Joomla 的 API 路由(com_ajax 或自建 component JSON 视图)
  2. 是否复用 JResponseJson 统一包装,而非手动拼字符串
  3. 是否做 CSRF/token 校验、权限校验、事务回滚、批量 ID 过滤
  4. 是否返回符合 HTTP 状态码、message、data 三要素的可扩展结构
  5. 是否兼顾调试模式下的异常栈隐藏与生产环境日志

知识点

  • Joomla API 路由:com_ajax、自建 component & format=json
  • JResponseJson:自动设置 application/json、统一 envelope、自动 500/403 状态
  • JSession::checkToken():防止 CSRF
  • JFactory::getUser()->authorise():行级权限
  • JTableObserver 或 CLI 批量事务:保证一致性
  • try/catch + JLog::add():生产环境不泄露敏感路径
  • 前端 axios/fetch 对接:data.success、data.message、data.data 三件套

答案

以下示例基于自建组件 com_article,路由 index.php?option=com_article&task=articles.batchRemove&format=json,代码可直接放入 Controller(site 或 admin 均可),满足 Joomla 4/5 原生规范。

<?php
defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Response\JsonResponse;
use Joomla\CMS\Table\Table;
use Joomla\Database\DatabaseInterface;

class ArticleControllerArticles extends BaseController
{
    public function batchRemove()
    {
        // 1. 防 CSRF
        $this->checkToken('request');

        // 2. 权限
        $user = Factory::getApplication()->getIdentity();
        if (!$user->authorise('core.delete', 'com_article')) {
            throw new RuntimeException('您无权删除文章', 403);
        }

        // 3. 接收参数
        $ids   = $this->input->get('cid', [], 'array');
        $ids   = array_filter(ArrayHelper::toInteger($ids));

        if (!$ids) {
            return new JsonResponse(null, '请选择要删除的文章', true);  // true 代表异常
        }

        $db    = Factory::getContainer()->get(DatabaseInterface::class);
        $table = Table::getInstance('ArticleTable', 'Joomla\\Component\\Article\\Administrator\\Table\\');

        $db->transactionStart();
        try {
            foreach ($ids as $id) {
                if (!$table->delete($id)) {
                    throw new RuntimeException($table->getError(), 500);
                }
            }
            $db->transactionCommit();
        } catch (Exception $e) {
            $db->transactionRollback();
            // 生产环境隐藏细节
            Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
            return new JsonResponse(null, '批量删除失败', true);
        }

        // 4. 返回标准 JSON
        return new JsonResponse(
            ['deleted' => count($ids)],   // data 区
            '成功删除 ' . count($ids) . ' 篇文章'  // message
        );
    }
}

关键点说明

  1. JsonResponse 会自动设置 Content-Type: application/json,并把数据包成 {success:bool, message:string, data:object|array, messages:[]},与 Joomla 核心完全对齐。
  2. 异常统一抛 RuntimeException,框架会捕获并返回 500,前端 axios 可直接判断 response.data.success。
  3. 事务包裹保证批量原子性,任何单条失败即整体回滚,符合国内金融/政府项目审计要求。
  4. 权限使用 core.delete 行级规则,可在后台“权限”面板细粒度配置,满足央企多角色场景。

拓展思考

  1. 大表优化:一次性 IN 删除可能锁表,可改为分段+LIMIT+异步队列,Joomla CLI 命令作为消费者,返回 202 Accepted 给前端轮询。
  2. 软删除:国内等保要求数据可恢复,可在表中加 state=-1 或 deleted_at 字段,JsonResponse 里返回逻辑删除行数而非物理删除。
  3. 事件驱动:触发 onContentAfterDelete 事件,同步清理 CDN 缓存、搜索引擎推送死链,保证 SEO 一致性。
  4. 统一异常处理:在组件入口加 setExceptionHandler,把 500 异常统一写入 JLog::add('BatchDelete:'.(string)$e, JLog::ERROR),方便运维接入 ELK。
  5. 前端体验:利用 Joomla 自带的 Joomla.submitbutton(token, task, form) 封装,可做到无刷新批量操作,同时兼容 Joomla 3 的老模板。