开发文档

Zerjie(择界)系统内核的完整开发参考——主题、插件、小工具、后台扩展、SEO 体系、核心 API、安全组件

简介

Zerjie(择界)是一款基于 纯原生 PHP 开发的主题驱动型内容管理系统。核心理念是「一核载万态 · 主题定乾坤」——内核只提供基础设施,业务逻辑完全由主题定义。

关键特点:

  • 零依赖:不依赖 Composer,不依赖任何 PHP 框架
  • 轻量:核心代码 1MB 以内,单文件入口
  • 三级扩展:主题 / 插件 / 小工具,互不耦合
  • 安全内建:CSRF、XSS、SQL 注入防护、IP 限流、分级防御、完整性校验开箱即用
  • SEO 内建:title / description / canonical / robots / OG / JSON-LD / sitemap.xml / robots.txt 一站式输出
  • 开箱即用:后台菜单、设置页、小工具管理、用户管理、SMTP、站点锁、CLI 命令全部内置
  • 多驱动:缓存 / 日志 / 队列都支持多驱动,可自由扩展

扩展体系一览:

类型位置职责
主题content/themes/{name}/定义整个站点的外观和前端路由
插件content/plugins/{name}/扩展功能,与主题无关
小工具content/widgets/ 或 core/widgets/可拖拽的前端内容块
内核边界:内核只提供「基础设施」——数据库、路由、认证、会话、钩子、缓存、日志、队列、安全组件、SEO 输出。业务逻辑(博客、论坛、商城等)一律由主题/插件实现。

环境要求

项目最低推荐
PHP7.48.1+
MySQL5.78.0+
MariaDB10.310.6+

必需扩展:pdo、pdo_mysql、json、openssl、zip。

推荐扩展:

  • intl:slug 音译(中文 → 拼音)
  • fileinfo:上传文件的 MIME 类型校验
  • curl:更新检查和完整性守卫优先使用,性能优于 allow_url_fopen
  • apcu:防火墙的限流可以走内存,性能更好
  • pcntl:队列 Worker 心跳与信号处理

安装与运行

上传源码到网站根目录,浏览器访问域名,自动跳转安装向导:

http://你的域名/install/install.php

安装流程(6 步):

  1. 启动界面(产品介绍)
  2. 用户协议
  3. 环境检测(PHP 版本、扩展、目录权限)
  4. 数据库配置(主机、端口、库名、用户名、密码、表前缀)
  5. 站点信息(标题、URL、管理员账号)
  6. 执行安装(创建表、写配置、生成 admin.php、删除 install/)

安装完成后:

  • 自动删除整个 install/ 目录
  • 后台入口默认为 admin.php(强烈建议重命名)
  • 配置文件写入 config/config.php(数据库)和 config/system.php(站点)
  • 站点 URL 写入 {prefix}options 表的 site_url 键
  • 核心文件的 SHA-256 清单写入 storage/manifest.json
  • 安装元数据(install_id、version)写入 storage/integrity/install.json
  • 根据 Web 服务器自动生成 .htaccess / web.config / nginx-routing-sample.txt

本地开发用 PHP 内置服务器即可:

cd /path/to/zerjie
php -S localhost:8080

目录结构

zerjie/
├── index.php                  前端入口
├── admin.php                  后台入口(可重命名)
├── console.php                CLI 入口
├── favicon.png                默认站点图标
├── config/                    配置目录
│   ├── config.php             数据库连接(安装时生成)
│   └── system.php             站点配置(安装时生成)
│
├── core/                      内核(不可修改)
│   ├── zerjie.php             内核引导文件
│   ├── auth.php               用户认证
│   ├── register.php           用户注册
│   ├── database/              数据库层
│   ├── security/              安全组件
│   ├── cache/                 缓存
│   ├── log/                   日志
│   ├── queue/                 队列
│   ├── router/                路由
│   ├── events/                事件系统
│   ├── http/                  HTTP 抽象
│   ├── session/               会话管理
│   ├── i18n/                  多语言
│   ├── update/                更新系统
│   ├── console/               CLI
│   ├── hook/                  钩子引擎
│   ├── exceptions/            异常处理
│   ├── widgets/               系统小工具
│   └── helpers/               全局辅助函数
│       ├── functions.php      核心辅助函数
│       ├── api.php            后台 / 小工具 / 设置 API
│       ├── mailer.php         SMTP 邮件
│       ├── seo.php            SEO 输出层
│       └── debug.php          调试工具
│
├── content/                   内容目录(用户可编辑)
│   ├── themes/                主题目录
│   ├── plugins/               插件目录
│   ├── widgets/               用户小工具目录
│   ├── languages/             用户语言包(覆盖系统)
│   ├── uploads/               上传文件
│   └── cache/                 生成的静态资源缓存
│
├── adminbackend/              后台管理界面
│   ├── AdminController.php    后台控制器
│   ├── admin-menu.php         默认后台菜单
│   ├── assets/                后台 JS / CSS
│   ├── languages/             系统语言包
│   └── view/                  后台视图
│
├── templates/                 系统级兜底模板
│   ├── activate.php           账号激活页
│   └── lock-pages/            站点锁页面模板
│
├── storage/                   运行时存储(禁止公开访问)
│   ├── cache/                 文件缓存
│   ├── logs/                  日志
│   ├── temp/                  临时文件
│   ├── queue/                 队列文件
│   ├── backups/               备份
│   ├── integrity/             完整性元数据
│   └── manifest.json          核心文件完整性清单
│
└── install/                   安装向导(安装后自动删除)

环境规则

Zerjie 使用单入口 index.php + PATH_INFO 风格的路由。需要 Web 服务器把所有非静态文件请求重写到 index.php,同时禁止直接访问 storage/、禁止执行 content/ 下的 PHP 文件。

必须配置的三条规则:
① 所有未命中的 URL 重写到 index.php;
② storage/ 目录禁止外部访问(内部全是运行时数据);
③ content/ 目录下的 .php 文件禁止执行(防止上传木马)。

Apache(含 .htaccess)

安装时如果检测到 Apache,会自动生成 .htaccess。如需手动确认,根目录的 .htaccess 应包含:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
Options -Indexes

storage/.htaccess(安装时自动生成):

<IfModule mod_authz_core.c>
    Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
    Order Deny,Allow
    Deny from all
</IfModule>

content/.htaccess(安装时自动生成,禁止执行 PHP):

Options -Indexes
<FilesMatch "\.(php|phtml|php3|php4|php5|phar)$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order Deny,Allow
        Deny from all
    </IfModule>
</FilesMatch>

前提:Apache 需启用 mod_rewrite,且虚拟主机 AllowOverride All(或至少 AllowOverride FileInfo Options)。

Nginx

安装时会生成 nginx-routing-sample.txt,把以下内容合并到虚拟主机 server { } 块中:

# 1. 路由重写(放在 server 块内)
location / {
    try_files $uri $uri/ /index.php?$args;
}

# 2. 禁止外部访问 storage/ 目录
location ^~ /storage/ {
    deny all;
    return 404;
}

# 3. 禁止执行 content/ 目录下的 PHP 文件
location ~ /content/(.*)\.(php|phtml|php3|php4|php5|phar)$ {
    deny all;
    return 403;
}

PHP 处理(FastCGI 示例):

location ~ \.php$ {
    fastcgi_pass   unix:/run/php/php-fpm.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

安全加固建议:

  • 隐藏 .htaccess 和 .git 目录(location ~ /\.(htaccess|git) { deny all; })
  • 限制上传大小(client_max_body_size 200m;,与后台「上传安装包」的 200MB 上限匹配)
  • 启用 gzip 压缩静态资源

IIS

安装时会生成 web.config。根目录的 web.config 应包含:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Zerjie Routing" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
        <directoryBrowse enabled="false" />
    </system.webServer>
</configuration>

前提:需安装 IIS URL Rewrite 模块;PHP 通过 FastCGI 配置。

Caddy

Caddy 使用 try_files 指令,无需额外重写规则:

:80 {
    root * /var/www/zerjie
    php_fastcgi unix//run/php/php-fpm.sock

    # 路由重写
    try_files {path} {path}/ /index.php?{query}

    # 禁止访问 storage/
    @storage {
        path /storage/*
    }
    respond @storage 404

    # 禁止执行 content/ 下的 PHP
    @contentPhp {
        path /content/*.php
    }
    respond @contentPhp 403

    # 静态文件服务
    file_server
}

目录权限

目录权限说明
config/755可读;system.php 需可写(用于后台改名同步)
storage/755(Web 用户可写)缓存、日志、临时文件都写入此处
content/755(Web 用户可写)主题、插件、上传文件
core/755只读
adminbackend/755只读
为什么禁止执行 content/ 下的 PHP:content/ 是用户可上传目录(主题 zip、插件 zip、缩略图等)。一旦上传逻辑被绕过,攻击者可以把 .php 伪装成 .jpg 上传,再通过 URL 直接访问执行。Web 服务器层禁止执行是最有效的兜底。

请求生命周期

每个 HTTP 请求的执行顺序(以 index.php 为例):

  1. 入口:index.php → core/zerjie.php
  2. 常量定义:ZERJIE_ROOT、ZERJIE_START、ZERJIE_CORE_DIR 等
  3. 卸载守卫:register_shutdown_function 注册 IntegrityGuard 检查钩子(如果已启用)
  4. 配置加载:config/config.php + config/system.php
  5. 自动加载器:注册 Zerjie\* 命名空间的 PSR-4 自动加载
  6. 维护模式:检测 storage/update/.maintenance 标志
  7. 会话启动:Zerjie\Session\Session::start()(仅 Web 请求)
  8. 安全响应头:X-Content-Type-Options、X-Frame-Options、CSP 等
  9. 完整性检查:比对 storage/manifest.json(任一文件被篡改 → 503)
  10. 错误处理:注册全局 error_handler 和 exception_handler
  11. 加载辅助函数:helpers/functions.php、api.php、mailer.php、seo.php
  12. 数据库连接:zerjie_database_connect()
  13. 预加载配置:从 options 表读 autoload = 'yes' 的所有键
  14. 多语言初始化:Zerjie\I18n\Language::init()
  15. 加载内核模块:auth.php、register.php
  16. 注册核心服务:Hook、Event Dispatcher、Cache Manager、Logger
  17. 加载插件:按 active_plugins 顺序 require 主文件
  18. 加载主题:require content/themes/{active}/functions.php
  19. 加载小工具:glob content/widgets/*.php
  20. 初始化路由:Router + Dispatcher + UrlGenerator
  21. 触发 zerjie_ready 钩子 ← 所有扩展的入口点
  22. 执行防御:Zerjie\Security\Defense::enforce()(非 CLI)
  23. robots.txt / sitemap.xml 拦截:系统级路径,不进入主题路由
  24. 匹配路由:Dispatcher 匹配 URL → 调用回调
  25. 输出响应:Response 对象 send
  26. 卸载:shutdown 钩子触发 IntegrityGuard 检查
关键点:所有主题/插件的注册代码都应该挂到 zerjie_ready 钩子。zerjie_ready 之前,内核只完成初始化,尚未加载任何业务代码。

钩子与过滤器

Zerjie 提供两套机制:Action(执行代码)和 Filter(修改数据)。

基础用法

// 注册 Action(执行代码,无返回值)
add_action('zerjie_ready', function () {
    // 内核初始化完成后执行
}, 10);

// 注册 Filter(修改数据,必须有返回值)
add_filter('zerjie_admin_menu', function ($menus) {
    $menus[] = ['slug' => 'my-page', 'title' => '我的页面'];
    return $menus;
}, 20);

// 触发 Action
do_action('my_custom_action', $arg1, $arg2);

// 应用 Filter
$result = apply_filters('my_custom_filter', $default_value, $arg1);

函数签名

函数参数返回值
add_action($hook, $callback, $priority = 10) 钩子名、回调、优先级 无
do_action($hook, ...$args) 钩子名、任意参数 无
add_filter($hook, $callback, $priority = 10) 钩子名、回调、优先级 无
apply_filters($hook, $value, ...$args) 钩子名、初始值、额外参数 被所有回调处理后的最终值

优先级

数字越小越先执行。相同优先级按注册顺序执行。

优先级场景
0-4内核早期处理(如建表、前置检查)
5-9主题/插件基础初始化
10(默认)常规处理
11-30晚于其他处理(如覆盖菜单、最终修改)
100+最后处理(如输出、记录)
注意:Filter 回调必须返回处理后的值。忘了 return 会导致下游收到 null。

事件系统

事件系统面向对象,适合插件做业务解耦。与钩子系统并存,二者互补。

基础用法

use Zerjie\Events\Event;

// 1. 触发事件
event('user.registered', new Event());

// 2. 监听事件
listen('user.registered', function ($event) {
    // 处理逻辑
}, 10);   // 第三个参数是优先级

携带数据

class UserRegisteredEvent extends \Zerjie\Events\Event {
    public $userId;
    public $username;
    public $email;

    public function __construct($userId, $username, $email) {
        $this->userId   = $userId;
        $this->username = $username;
        $this->email    = $email;
    }
}

// 触发
event('user.registered', new UserRegisteredEvent(123, 'alice', 'alice@example.com'));

// 监听
listen('user.registered', function ($e) {
    echo "新用户:{$e->username}(ID: {$e->userId})";
});

中止传播

listen('order.created', function ($event) {
    if (/* 停止后续监听 */) {
        $event->stopPropagation();
    }
});

事件 vs 钩子的选择

场景推荐
需要修改返回值过滤器 Filter
只需执行副作用(发通知、写日志)动作 Action 或事件 Event
业务解耦、领域事件事件 Event(面向对象)
需要中止传播事件 Event(有 stopPropagation)
快速注册、简单处理钩子 Action/Filter

主题结构

在 content/themes/ 下新建目录,例如 my-theme/:

content/themes/my-theme/
├── theme.json              主题元信息(必需)
├── functions.php           主题逻辑入口
├── schema.php              私有数据表(可选)
├── templates/              模板目录
│   ├── partials/           公共片段
│   │   ├── header.php
│   │   └── footer.php
│   ├── index.php           首页
│   ├── single.php          单篇详情
│   └── 404.php             错误页
├── admin/                  后台视图(可选)
│   └── settings.php
└── assets/                 静态资源
    ├── css/style.css
    └── js/main.js

启用主题:

  • 后台 → 外观 → 主题 → 找到你的主题 → 点击启用
  • 或 CLI:php console.php theme:activate my-theme

theme.json

主题的身份标识。用于后台主题管理页面,以及判断主题唯一性(同一 id 视为同一主题的不同版本)。

{
    "id": "my-theme",
    "name": "我的主题",
    "version": "1.0.0",
    "author": "Your Name",
    "description": "一个简洁的博客主题",
    "homepage": "https://example.com"
}
字段必需说明
id是唯一标识,用于判断同一主题(同名目录不同 id 视为不同主题)
name是显示名称
version推荐语义化版本号
author否作者
description否描述
homepage否主题主页
同 id 视为同一主题:上传新版本时,系统会用 id 匹配。如果 id 一致、版本号不同,会备份旧目录并覆盖;id 不一致则拒绝(防止同名覆盖不同主题)。

模板系统

内核不规定主题的目录结构,主题必须通过 filter 显式注册模板路径。这是为了让主题完全掌控自己的文件布局。

注册模板路径

<?php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

add_filter('zerjie_theme_template_file', function ($file, $template, $theme) {
    if ($theme !== 'my-theme') return $file;

    // 白名单:只接管本主题提供的模板
    $allowed = ['index', 'single', 'page', '404'];
    if (!in_array($template, $allowed, true)) return $file;

    $path = __DIR__ . '/templates/' . $template . '.php';
    return file_exists($path) ? $path : $file;
}, 10, 3);

模板查找顺序

  1. 触发 zerjie_theme_template_file filter(主题返回自己的路径)
  2. 兜底:ZERJIE_ROOT/templates/{tpl}.php(系统级模板)

模板中可用的辅助函数

函数说明
Helper::e($str)HTML 转义输出(防 XSS)
zerjie_get_option($key, $default)读取配置
zerjie_get_current_user()当前登录用户(未登录返回 null)
zerjie_current_user_can($cap)权限检查
zerjie_is_logged_in()是否已登录
__($text) / _e($text)多语言(返回 / 输出)
csrf_field()输出 CSRF 隐藏字段
csrf_token()返回当前 CSRF 令牌
the_widgets($area)输出指定区域的小工具
zerjie_client_ip()获取真实客户端 IP
zerjie_get_favicon_url()获取 favicon URL
flash_get($key)读取一次性 flash 消息
js_config($extra)输出全局 JS 配置属性(含 CSRF、当前用户)
js_data($data, $key)输出自定义 data-* JSON 属性
zerjie_seo_head()输出全部 SEO 标签(title / meta / og / jsonld)

完整示例:首页模板

<?php
// templates/index.php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

$site_title = zerjie_get_option('site_title', 'Zerjie');
$posts = zerjie_db_query('posts', ['status' => 'published'], ['*'], ['id' => 'DESC'], 10);

require __DIR__ . '/partials/header.php';
?>

<main class="container">
    <h1><?= Helper::e($site_title) ?></h1>

    <?php foreach ($posts as $post): ?>
        <article class="post-card">
            <h2><?= Helper::e($post['title']) ?></h2>
            <p><?= Helper::e(mb_substr(strip_tags($post['content']), 0, 200)) ?>…</p>
        </article>
    <?php endforeach; ?>
</main>

<?php require __DIR__ . '/partials/footer.php'; ?>

路由注册

在 functions.php 里通过 zerjie_ready 钩子注册路由。

add_action('zerjie_ready', function () {
    global $zerjie_router;
    if (!$zerjie_router) return;

    $zerjie_router->get('/', function () {
        require __DIR__ . '/templates/index.php';
        exit;
    });

    $zerjie_router->get('/post/{id:\d+}', function ($id) {
        require __DIR__ . '/templates/single.php';
        exit;
    });

    $zerjie_router->post('/contact', function () {
        if (!csrf_check()) {
            die('CSRF 校验失败');
        }
        flash_success('提交成功');
        header('Location: /contact');
        exit;
    });
});

Route 对象方法

方法说明
->name($name)命名路由,可通过 route() 生成 URL
->middleware($mw)绑定中间件(字符串类名 / 闭包)

路由分组

$zerjie_router->group('/api/v1', function ($router) {
    $router->get('/users',  function () { /* GET /api/v1/users */ });
    $router->post('/users', function () { /* POST /api/v1/users */ });
});

生成 URL

// 注册时命名
$zerjie_router->get('/post/{id}', function ($id) { /* ... */ })->name('post');

// 生成 URL
$url = route('post', ['id' => 123]);   // → /post/123

参数约束

$zerjie_router->get('/post/{id:\d+}', function ($id) { /* ... */ });
$zerjie_router->get('/user/{name:[a-zA-Z0-9_]+}', function ($name) { /* ... */ });
$zerjie_router->get('/category/{slug}', function ($slug) { /* ... */ });

主题私有表

主题可以携带自己的数据表定义,随主题启用时自动创建,不污染系统安装脚本。所有表名统一加系统前缀,与内核共享同一数据库。

schema.php 格式

<?php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

return [
    "CREATE TABLE IF NOT EXISTS `{prefix}my_posts` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `title` VARCHAR(191) NOT NULL,
        `content` TEXT,
        `created_at` DATETIME NOT NULL,
        INDEX `created_idx` (`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
];

functions.php 中触发建表

add_action('zerjie_ready', function () {
    static $done = false;
    if ($done) return;

    $db = $GLOBALS['zerjie_db'] ?? null;
    if (!$db instanceof \PDO) return;

    $file = __DIR__ . '/schema.php';
    if (!file_exists($file)) { $done = true; return; }

    $tables = include $file;
    $prefix = zerjie_table_prefix();
    foreach ($tables as $sql) {
        $sql = str_replace('{prefix}', $prefix, trim((string) $sql));
        try { $db->exec($sql); } catch (\PDOException $e) {}
    }
    $done = true;
}, 5);   // 优先级 5,早于业务钩子
注意事项:
· 用 CREATE TABLE IF NOT EXISTS,保证幂等
· 开发阶段直接删表重建;生产环境字段变更走 database/migrations/
· 表名建议加主题前缀(如 forum_、shop_),避免与其他主题/插件冲突

完整示例:最小博客主题

theme.json

{
    "id": "my-blog",
    "name": "我的博客",
    "version": "1.0.0",
    "description": "极简博客主题"
}

schema.php

<?php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

return [
    "CREATE TABLE IF NOT EXISTS `{prefix}blog_posts` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `title` VARCHAR(255) NOT NULL,
        `content` LONGTEXT,
        `status` ENUM('draft','published') DEFAULT 'published',
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX `status_created` (`status`, `created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
];

functions.php

<?php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

// 1. 注册模板路径
add_filter('zerjie_theme_template_file', function ($file, $template, $theme) {
    if ($theme !== 'my-blog') return $file;
    $allowed = ['index', 'single', '404'];
    if (!in_array($template, $allowed, true)) return $file;
    $path = __DIR__ . '/templates/' . $template . '.php';
    return file_exists($path) ? $path : $file;
}, 10, 3);

// 2. 自动建表
add_action('zerjie_ready', function () {
    static $done = false;
    if ($done) return;
    $done = true;

    $db = $GLOBALS['zerjie_db'] ?? null;
    if (!$db) return;

    $file = __DIR__ . '/schema.php';
    if (!file_exists($file)) return;

    $tables = include $file;
    $prefix = zerjie_table_prefix();
    foreach ($tables as $sql) {
        $sql = str_replace('{prefix}', $prefix, trim($sql));
        try { $db->exec($sql); } catch (\PDOException $e) {}
    }
}, 5);

// 3. 注册路由
add_action('zerjie_ready', function () {
    global $zerjie_router;
    if (!$zerjie_router) return;

    $zerjie_router->get('/', function () {
        $db = $GLOBALS['zerjie_db'];
        $prefix = zerjie_table_prefix();
        $posts = $db->query("SELECT * FROM `{$prefix}blog_posts` WHERE status = 'published' ORDER BY id DESC LIMIT 20")->fetchAll();
        require __DIR__ . '/templates/index.php';
        exit;
    });

    $zerjie_router->get('/post/{id:\d+}', function ($id) {
        $db = $GLOBALS['zerjie_db'];
        $prefix = zerjie_table_prefix();
        $stmt = $db->prepare("SELECT * FROM `{$prefix}blog_posts` WHERE id = ? AND status = 'published'");
        $stmt->execute([(int) $id]);
        $post = $stmt->fetch();

        if (!$post) {
            http_response_code(404);
            require __DIR__ . '/templates/404.php';
            exit;
        }

        require __DIR__ . '/templates/single.php';
        exit;
    });
});

插件结构

在 content/plugins/ 下新建目录:

content/plugins/my-plugin/
├── plugin.json          插件元信息
├── my-plugin.php        主文件(名称必须与目录名一致)
├── includes/            辅助 PHP 文件(可选)
└── assets/              静态资源(可选)

plugin.json:

{
    "id": "my-plugin",
    "name": "我的插件",
    "version": "1.0.0",
    "author": "Your Name",
    "description": "一个简单的示例插件"
}

主文件 my-plugin.php:

<?php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

add_action('zerjie_ready', function () {
    // 插件初始化
});

启用/禁用:

  • 后台 → 插件管理 → 找到插件 → 点击启用/禁用
  • 或 CLI:php console.php plugin:activate my-plugin

钩子注册

注册后台菜单

add_action('zerjie_ready', function () {
    add_filter('zerjie_admin_menu', function ($menus) {
        $menus[] = [
            'slug'              => 'my-plugin-page',
            'title'             => '我的插件',
            'icon'              => '🚀',
            'view_capability'   => 'manage_options',
            'manage_capability' => 'manage_options',
            'position'          => 60,
            'callback'          => 'my_plugin_render_page',
        ];
        return $menus;
    }, 20);
});

function my_plugin_render_page() {
    echo '<div style="padding:24px 30px;">';
    echo '<h2>我的插件</h2>';
    echo '</div>';
}

注入后台 CSS / JS

add_action('zerjie_admin_head', function () {
    echo '<link rel="stylesheet" href="/content/plugins/my-plugin/assets/admin.css">';
});

add_action('zerjie_admin_footer', function () {
    $ver = filemtime(__DIR__ . '/assets/admin.js');
    echo '<script src="/content/plugins/my-plugin/assets/admin.js?v=' . $ver . '"></script>';
});

注册设置字段

add_action('zerjie_ready', function () {
    setting_field_register('advanced', 'my_api_key', [
        'label'       => 'API Key',
        'type'        => 'text',
        'default'     => '',
        'description' => '第三方服务的 API 密钥',
    ]);
});

// 读取
$key = get_setting('my_api_key', '');

// 更新
update_setting('my_api_key', 'sk-xxx');

事件监听

add_action('zerjie_ready', function () {
    listen('user.registered', function ($e) {
        if ($e instanceof \App\Events\UserRegisteredEvent) {
            zerjie_send_mail($e->email, '欢迎', '欢迎加入!');
        }
    });
});

完整示例:访问统计插件

plugin.json

{
    "id": "visit-stats",
    "name": "访问统计",
    "version": "1.0.0",
    "description": "记录每天的访问量"
}

visit-stats.php

<?php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

// 建表
add_action('zerjie_ready', function () {
    if (zerjie_get_option('visit_stats_installed') === '1') return;

    $db = $GLOBALS['zerjie_db'];
    $prefix = zerjie_table_prefix();

    $db->exec("CREATE TABLE IF NOT EXISTS `{$prefix}visit_stats` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `date` DATE NOT NULL,
        `count` INT DEFAULT 0,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY `date` (`date`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    zerjie_update_option('visit_stats_installed', '1');
}, 5);

// 每次前台请求 +1
add_action('zerjie_ready', function () {
    if (defined('ZERJIE_ADMIN_ENTRY') && ZERJIE_ADMIN_ENTRY) return;

    $db = $GLOBALS['zerjie_db'];
    $prefix = zerjie_table_prefix();
    $today = date('Y-m-d');

    $db->prepare("INSERT INTO `{$prefix}visit_stats` (date, count) 
                  VALUES (?, 1) 
                  ON DUPLICATE KEY UPDATE count = count + 1")
       ->execute([$today]);
}, 100);

注册小工具

小工具文件放在 content/widgets/ 或 core/widgets/,内核自动加载所有 .php。

<?php
// content/widgets/my-widget.php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

add_action('zerjie_ready', function () {
    widget_register(
        'my-widget',              // 唯一 ID
        '我的小工具',              // 显示名称
        function () {             // 渲染回调
            ?>
            <div class="widget-my">
                <h3>我的小工具</h3>
                <p>这是小工具内容</p>
            </div>
            <?php
        },
        [
            'sidebar'  => 'sidebar',   // 默认区域
            'position' => 10,          // 排序位置
        ]
    );
});
参数类型说明
$idstring唯一 ID(英文小写、连字符)
$namestring后台显示名称
$callbackcallable渲染回调,输出 HTML
$params['sidebar']string默认放置区域
$params['position']int排序位置(小的在前)
$params['editable']bool是否可编辑(默认 false)
$params['render_edit']callable返回编辑表单 HTML
$params['save_edit']callable处理编辑提交

前端输出小工具

<aside class="sidebar">
    <?php the_widgets('sidebar'); ?>
</aside>

自定义区域

主题/插件可以通过 widget_area_register() 声明自己支持的小工具区域,后台「小工具管理」会自动渲染这些区域,不再强制使用内置的 hero / main / sidebar。

// 在主题的 functions.php 中声明区域
widget_area_register('sidebar', __('Sidebar'), [
    'description' => __('Right column sidebar'),
    'priority'    => 20,
    'icon'        => '📌',
]);

widget_area_register('footer-1', __('Footer Column 1'), [
    'priority' => 30,
    'icon'     => '🦶',
]);

widget_area_register('footer-2', __('Footer Column 2'), [
    'priority' => 31,
    'icon'     => '🦶',
]);
参数说明
$id区域唯一标识(小写字母、数字、下划线、连字符)
$name显示名称(会被翻译)
$args['description']区域描述
$args['priority']排序,越小越靠前(默认 10)
$args['icon']图标 emoji(默认 📦)
向后兼容:如果主题/插件从未调用 widget_area_register(),系统会自动回退到内置的 hero / main / sidebar,现有主题无需修改。unplaced(未放置)是系统保留区域,禁止注册。

前端调用

<!-- 在主题模板中的任意位置 -->
<div class="sidebar">
    <?php the_widgets('sidebar'); ?>
</div>

<footer>
    <div class="col-1"><?php the_widgets('footer-1'); ?></div>
    <div class="col-2"><?php the_widgets('footer-2'); ?></div>
</footer>

可编辑小工具

让小工具在后台可以配置参数。需要额外提供 3 个字段:editable => true、render_edit、save_edit。

add_action('zerjie_ready', function () {
    widget_register(
        'my-banner',
        '我的横幅',
        // 前端渲染
        function () {
            $inst = $GLOBALS['current_widget_instance'] ?? [];
            $instance_id = $inst['instance_id'] ?? 'default';
            $data = zerjie_get_option('my_banner_data', []);
            $conf = $data[$instance_id] ?? ['title' => '', 'color' => '#000'];

            echo '<div style="background:' . Helper::e($conf['color']) . ';padding:20px;">';
            echo '<h3>' . Helper::e($conf['title']) . '</h3>';
            echo '</div>';
        },
        [
            'sidebar'  => 'sidebar',
            'position' => 20,
            'editable' => true,

            // 后台编辑表单
            'render_edit' => function ($instance_id) {
                $data = zerjie_get_option('my_banner_data', []);
                $conf = $data[$instance_id] ?? ['title' => '', 'color' => '#000'];
                ob_start();
                ?>
                <div class="form-group">
                    <label>标题</label>
                    <input type="text" name="title" value="<?= Helper::e($conf['title']) ?>">
                </div>
                <div class="form-group">
                    <label>颜色</label>
                    <input type="color" name="color" value="<?= Helper::e($conf['color']) ?>">
                </div>
                <?php
                return ob_get_clean();
            },

            // 保存
            'save_edit' => function ($instance_id, $post_data) {
                $data = zerjie_get_option('my_banner_data', []);
                $data[$instance_id] = [
                    'title' => trim($post_data['title'] ?? ''),
                    'color' => trim($post_data['color'] ?? '#000'),
                ];
                zerjie_update_option('my_banner_data', $data);
                return ['success' => true, 'message' => '已保存'];
            },
        ]
    );
});

完整示例:最新文章小工具

<?php
// content/widgets/latest-posts.php
if (!defined('ZERJIE_ROOT')) die('Access denied.');

add_action('zerjie_ready', function () {
    widget_register(
        'latest-posts',
        '最新文章',
        function () {
            $inst = $GLOBALS['current_widget_instance'] ?? [];
            $instance_id = $inst['instance_id'] ?? 'default';
            $data = zerjie_get_option('latest_posts_data', []);
            $conf = $data[$instance_id] ?? ['limit' => 5, 'show_date' => true];

            $db = $GLOBALS['zerjie_db'];
            $prefix = zerjie_table_prefix();
            $limit = max(1, min(20, (int) $conf['limit']));

            $stmt = $db->query("SELECT id, title, created_at FROM `{$prefix}posts` 
                                WHERE status = 'published' 
                                ORDER BY created_at DESC 
                                LIMIT {$limit}");
            $posts = $stmt->fetchAll();

            echo '<h3 class="widget-title">最新文章</h3>';
            echo '<ul class="widget-post-list">';
            foreach ($posts as $p) {
                echo '<li>';
                echo '<a href="/post/' . (int) $p['id'] . '">' . Helper::e($p['title']) . '</a>';
                if (!empty($conf['show_date'])) {
                    echo ' <time>' . Helper::e($p['created_at']) . '</time>';
                }
                echo '</li>';
            }
            echo '</ul>';
        },
        [
            'sidebar'  => 'sidebar',
            'position' => 5,
            'editable' => true,

            'render_edit' => function ($instance_id) {
                $data = zerjie_get_option('latest_posts_data', []);
                $conf = $data[$instance_id] ?? ['limit' => 5, 'show_date' => true];
                ob_start();
                ?>
                <div class="form-group">
                    <label>显示数量</label>
                    <input type="number" name="limit" 
                           value="<?= (int) $conf['limit'] ?>" min="1" max="20">
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="show_date" value="1" 
                               <?= !empty($conf['show_date']) ? 'checked' : '' ?>>
                        显示日期
                    </label>
                </div>
                <?php
                return ob_get_clean();
            },

            'save_edit' => function ($instance_id, $post_data) {
                $data = zerjie_get_option('latest_posts_data', []);
                $data[$instance_id] = [
                    'limit'     => max(1, min(20, (int) ($post_data['limit'] ?? 5))),
                    'show_date' => !empty($post_data['show_date']),
                ];
                zerjie_update_option('latest_posts_data', $data);
                return ['success' => true, 'message' => '已保存'];
            },
        ]
    );
});

注册后台菜单

方式 1:函数式

add_action('zerjie_ready', function () {
    admin_menu_register(
        '我的页面',                   // 菜单标题
        function () {                 // 回调(渲染页面)
            echo '<div style="padding:24px 30px;">';
            echo '<h2>我的页面</h2>';
            echo '</div>';
        },
        '🚀',                         // 图标
        60,                           // 位置(越小越靠前)
        'manage_options'              // 所需权限
    );
}, 20);

方式 2:filter 式

add_filter('zerjie_admin_menu', function ($menus) {
    $menus[] = [
        'slug'              => 'my-page',
        'title'             => '我的页面',
        'icon'              => '🚀',
        'view_capability'   => 'view_my_page',
        'manage_capability' => 'manage_my_page',
        'position'          => 60,
        'callback'          => function () {
            require __DIR__ . '/admin/page.php';
        },
    ];
    return $menus;
}, 20);
字段说明
slug唯一标识,URL 会带 ?action=slug
title菜单显示名称
iconEmoji 图标
view_capability能否看见此菜单(默认 read)
manage_capability能否执行管理操作(默认 manage_options)
position排序位置(小的靠前)
callback渲染回调(可传函数名或闭包)
children子菜单数组(可选)

权限名称会自动出现在 后台 → 用户 → 权限 页面供管理员分配。

注册设置字段

让插件的配置出现在后台「系统设置」页中。

add_action('zerjie_ready', function () {
    setting_field_register('advanced', 'my_api_key', [
        'label'       => 'API Key',
        'type'        => 'text',
        'default'     => '',
        'description' => '第三方服务的 API 密钥',
    ]);

    setting_field_register('advanced', 'my_enabled', [
        'label'   => '启用功能',
        'type'    => 'checkbox',
        'default' => '1',
    ]);

    setting_field_register('advanced', 'my_mode', [
        'label'   => '模式',
        'type'    => 'select',
        'default' => 'auto',
        'options' => ['auto' => '自动', 'manual' => '手动'],
    ]);
}, 10);
// 读取(自动加 'setting_' 前缀)
$apiKey = get_setting('my_api_key', '');

// 更新
update_setting('my_api_key', 'sk-xxxxxxxx');

支持的字段类型:text、email、textarea、select、checkbox、number、password。

注入 CSS / JS

// 注入到后台 <head>
add_action('zerjie_admin_head', function () {
    echo '<link rel="stylesheet" href="/content/plugins/my-plugin/assets/admin.css">';
});

// 注入到后台 </body> 前
add_action('zerjie_admin_footer', function () {
    $ver = filemtime(__DIR__ . '/assets/admin.js');
    echo '<script src="/content/plugins/my-plugin/assets/admin.js?v=' . $ver . '"></script>';
});
钩子类型说明
zerjie_admin_headAction后台 <head> 输出
zerjie_admin_footerAction后台 </body> 前输出
zerjie_admin_topbarAction顶栏输出
zerjie_admin_footer_beforeAction页脚前
zerjie_admin_footer_afterAction页脚后
zerjie_admin_footer_textFilter页脚文字
zerjie_admin_page_content_{action}Filter替换某个后台页面内容
zerjie_admin_layout_fileFilter替换后台整体布局
zerjie_admin_login_fileFilter替换后台登录页
zerjie_dashboard_widgetsFilter仪表盘小部件

SEO 配置项

所有 SEO 配置集中在后台 系统设置,无需额外页面。

配置 key说明
site_title站点标题
subtitle站点副标题(首页标题会拼接)
site_description站点描述(meta description 兜底)
site_url站点 URL(canonical / OG / sitemap 基础)
title_separator站点标题与副标题的连接符(默认 -)
page_title_separator页面标题与站点名之间的连接符(默认 |)
seo_keywordsmeta keywords(可选)
seo_twitter_sitetwitter:site(可选)
seo_sitemap_enabled是否生成 /sitemap.xml(默认 1)
seo_robots_contentrobots.txt 内容(留空用默认)
og_default_image默认分享图(og:image / twitter:image 兜底)
logo_lightOrganization JSON-LD 的 logo
faviconfavicon 图标

zerjie_seo_head()

一站式 SEO 输出。主题只需在 <head> 里调用一次,即可输出 title / description / keywords / robots / canonical / OG / Twitter Card / JSON-LD。

<?php
// partials/header.php
require __DIR__ . '/partials/header.php';
?>
<!DOCTYPE html>
<html lang="<?= Helper::e(get_language()) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <?php zerjie_seo_head(); ?>

    <link rel="stylesheet" href="/assets/style.css">
</head>
<body>

输出顺序

  1. <title>
  2. <meta name="description">(有内容时)
  3. <meta name="keywords">(有配置时)
  4. <meta name="robots">
  5. <link rel="canonical">(非 404 页面)
  6. <meta property="og:*">(非 404 页面)
  7. <meta name="twitter:*">(非 404 页面)
  8. <script type="application/ld+json">(非 404 页面)

页面类型判定

系统根据 URL 自动判断页面类型,影响 title 拼接与 robots:

类型URL 示例title 规则robots
home/站点标题 + 连接符 + 副标题index, follow
singular/post/1页面标题 + 连接符 + 站点标题index, follow
taxonomy/category/news同上index, follow
search/search同上noindex, follow
login/login同上noindex, follow
register/register同上noindex, follow
404任意未匹配同上noindex, follow
分页:?page=N(N > 1)自动 noindex,避免重复内容。canonical 保留 ?page=N。

页面数据注入

主题可以在调用 zerjie_seo_head() 之前通过全局变量与 filter 注入数据。

全局变量

// 页面标题(优先级高于 $GLOBALS['pageTitle'])
$GLOBALS['zerjie_seo_title'] = '文章标题';

// 页面描述(优先级高于 site_description)
$GLOBALS['zerjie_seo_description'] = '文章摘要...';

// 内容摘要(description 未设置时使用)
$GLOBALS['zerjie_seo_excerpt'] = '摘要文本';

// 页面标题(低优先级)
$pageTitle = '文章标题';

Filter

Filter参数说明
zerjie_seo_page_type$type覆盖页面类型判断
zerjie_seo_page_title$title覆盖页面标题
zerjie_seo_title_full$full, $pageTitle, $siteTitle覆盖最终完整 title
zerjie_seo_meta_description_text$desc覆盖 meta description
zerjie_seo_canonical_url$url覆盖 canonical URL
zerjie_seo_robots$robots覆盖 robots meta
zerjie_seo_open_graph_tags$tags(关联数组)覆盖 OG 标签
zerjie_seo_twitter_tags$tags(关联数组)覆盖 Twitter Card
zerjie_seo_jsonld$schemas(数组)追加/修改 JSON-LD
zerjie_seo_head_output$output最终输出前整体覆盖

示例:单页 SEO 覆盖

// 在渲染详情页的模板/控制器里
$GLOBALS['zerjie_seo_title']       = $article['title'];
$GLOBALS['zerjie_seo_description'] = mb_substr(strip_tags($article['content']), 0, 160);

// 追加 Article Schema
add_filter('zerjie_seo_jsonld', function ($schemas) use ($article) {
    $schemas[] = [
        '@context'      => 'https://schema.org',
        '@type'         => 'Article',
        'headline'      => $article['title'],
        'datePublished' => $article['created_at'],
        'dateModified'  => $article['updated_at'],
        'author'        => ['@type' => 'Person', 'name' => $article['author']],
    ];
    return $schemas;
});

require __DIR__ . '/partials/header.php';   // 这里会调用 zerjie_seo_head()

示例:帖子专属分享图

if (!empty($topic['cover_image'])) {
    add_filter('zerjie_seo_open_graph_tags', function ($tags) use ($topic) {
        $tags['og:image'] = '/content/uploads/' . ltrim($topic['cover_image'], '/');
        return $tags;
    });
}

扩展 JSON-LD

系统默认输出 Organization(全站)与 WebSite(仅首页)。主题/插件通过 zerjie_seo_jsonld filter 追加业务 Schema。

可用的辅助函数

函数说明
zerjie_seo_jsonld()输出一段 JSON-LD

示例:Article Schema

add_filter('zerjie_seo_jsonld', function ($schemas) use ($article) {
    if (zerjie_seo_current_page_type() === 'singular') {
        $schemas[] = [
            '@context'      => 'https://schema.org',
            '@type'         => 'Article',
            'headline'      => $article['title'],
            'datePublished' => date('c', strtotime($article['created_at'])),
            'dateModified'  => date('c', strtotime($article['updated_at'])),
            'author'        => ['@type' => 'Person', 'name' => $article['author']],
        ];
    }
    return $schemas;
});

示例:BreadcrumbList

add_filter('zerjie_seo_jsonld', function ($schemas) use ($topic) {
    $schemas[] = [
        '@context'        => 'https://schema.org',
        '@type'           => 'BreadcrumbList',
        'itemListElement' => [
            ['@type' => 'ListItem', 'position' => 1, 'name' => '首页',   'item' => '/'],
            ['@type' => 'ListItem', 'position' => 2, 'name' => '论坛',   'item' => '/forum'],
            ['@type' => 'ListItem', 'position' => 3, 'name' => $topic['title'], 'item' => '/forum/topic/' . $topic['id']],
        ],
    ];
    return $schemas;
});

扩展 sitemap

系统 /sitemap.xml 默认包含:首页 + 所有分类。主题/插件通过 zerjie_seo_sitemap_urls filter 追加内容。

add_action('zerjie_ready', function () {
    add_filter('zerjie_seo_sitemap_urls', function ($urls, $siteUrl) {
        $now = date('c');

        // 追加静态页
        foreach (['/docs', '/forum', '/releases'] as $path) {
            $urls[] = [
                'loc'        => $siteUrl . $path,
                'lastmod'    => $now,
                'changefreq' => 'weekly',
                'priority'   => '0.7',
            ];
        }

        // 追加内容项
        $db = $GLOBALS['zerjie_db'];
        $prefix = zerjie_table_prefix();
        $stmt = $db->query("SELECT slug, updated_at FROM `{$prefix}articles`");
        foreach ($stmt->fetchAll() as $row) {
            $urls[] = [
                'loc'        => $siteUrl . '/article/' . rawurlencode($row['slug']),
                'lastmod'    => date('c', strtotime($row['updated_at'])),
                'changefreq' => 'weekly',
                'priority'   => '0.6',
            ];
        }

        return $urls;
    }, 10, 2);
}, 20);

URL 条目结构

字段必需说明
loc是完整 URL(含 site_url 前缀)
lastmod否ISO 8601 日期(date('c'))
changefreq否always / hourly / daily / weekly / monthly
priority否0.0 ~ 1.0 的字符串

另有 zerjie_seo_sitemap_xml filter 可整体覆盖最终 XML 输出。

robots.txt

系统层 zerjie.php 会在路由分发前拦截 /robots.txt,直接调用 zerjie_seo_robots_txt() 输出。

内容来源

  1. 优先读 seo_robots_content option(后台「系统设置 → SEO · 抓取配置」可编辑)
  2. 为空时使用默认内容:
User-agent: *
Disallow: /admin.php
Disallow: /adminbackend/
Disallow: /storage/
Disallow: /content/plugins/
Allow: /

自动追加 sitemap

当 seo_sitemap_enabled = 1 且内容中没有 Sitemap: 行时,系统自动追加:

Sitemap: https://your-domain.com/sitemap.xml

Filter 覆盖

add_filter('zerjie_seo_robots_txt_content', function ($content) {
    $content .= "\nCrawl-delay: 2\n";
    return $content;
});
说明:robots.txt 与 sitemap.xml 的路由由系统层统一拦截,主题/插件不要再注册这两个路径,否则不会生效(系统层已经 exit)。

配置读写

所有配置存储在 {prefix}options 表。读取时会缓存到内存,同一请求内多次读取零成本。

读取配置

// 读取(不存在时返回默认值)
$title = zerjie_get_option('site_title', 'Zerjie');
$color = zerjie_get_option('theme_primary_color', '#2563eb');

// 读取数组(自动反序列化)
$settings = zerjie_get_option('my_plugin_settings', []);

写入配置

// 写入字符串
zerjie_update_option('site_title', '我的网站');

// 存储数组(自动序列化)
zerjie_update_option('my_plugin_settings', [
    'enabled' => true,
    'color'   => '#2563eb',
]);

// 存储数字
zerjie_update_option('my_counter', 42);

autoload 白名单

下列 key 会被预加载(安装/首次请求时一次性读入内存),其他 key 首次读取时才查库:

site_title, subtitle, site_description, site_url,
title_separator, page_title_separator,
active_plugins, nav_menu_primary, role_caps,
admin_allowed_roles, site_lock_enabled,
widget_placements, allow_registration,
seo_keywords, seo_twitter_site, seo_sitemap_enabled,
seo_robots_content, og_default_image

如需频繁读取自定义配置,在 core/helpers/functions.php 的 $autoloadKeys 数组中添加 key。

数据库操作

方式一:辅助函数

查询:zerjie_db_query()

// 签名:zerjie_db_query($table, $where = [], $select = ['*'], $order = [], $limit = null)
$users = zerjie_db_query(
    'users',
    ['role' => 'admin'],
    ['id', 'username', 'email'],
    ['id' => 'DESC'],
    10
);

插入:zerjie_db_insert()

// 签名:zerjie_db_insert($table, $data) → 返回自增 ID
$userId = zerjie_db_insert('users', [
    'username' => 'alice',
    'email'    => 'alice@example.com',
    'password' => password_hash('secret', PASSWORD_DEFAULT),
    'role'     => 'user',
    'status'   => 'active',
]);

更新:zerjie_db_update()

// 签名:zerjie_db_update($table, $data, $where) → 返回影响行数
$affected = zerjie_db_update('users', ['status' => 'banned'], ['id' => 5]);

删除:zerjie_db_delete()

// 签名:zerjie_db_delete($table, $where) → 返回影响行数
$affected = zerjie_db_delete('logs', ['id' => 100]);

方式二:原生 PDO

$db = $GLOBALS['zerjie_db'];
$prefix = zerjie_table_prefix();

$stmt = $db->prepare("
    SELECT u.username, COUNT(p.id) AS post_count
    FROM `{$prefix}users` u
    LEFT JOIN `{$prefix}posts` p ON p.author_id = u.id
    WHERE u.status = ?
    GROUP BY u.id
    HAVING post_count > ?
    ORDER BY post_count DESC
    LIMIT 10
");
$stmt->execute(['active', 5]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

方式三:QueryBuilder(流式)

$db = $GLOBALS['zerjie_db'];
$qb = new \Zerjie\Database\QueryBuilder($db, 'users');

$users = $qb->select(['id', 'username', 'email'])
           ->where('role', '=', 'admin')
           ->where('status', '=', 'active')
           ->orderBy('id', 'DESC')
           ->limit(10)
           ->get();

// 获取单条
$user = $qb->where('id', '=', 5)->first();

// 分页
$page = $qb->paginate(20, 1);
// → ['items' => [...], 'total' => 100, 'per_page' => 20, 'current_page' => 1, 'last_page' => 5]

事务

$db = $GLOBALS['zerjie_db'];

try {
    $db->beginTransaction();

    $db->prepare("UPDATE `{$prefix}users` SET balance = balance - ? WHERE id = ?")
       ->execute([100, $fromId]);
    $db->prepare("UPDATE `{$prefix}users` SET balance = balance + ? WHERE id = ?")
       ->execute([100, $toId]);

    $db->commit();
} catch (\PDOException $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    throw $e;
}
安全提示:永远不要拼接用户输入到 SQL。所有用户输入用 ? 占位符或 bindValue() 传递。

用户与权限

登录状态

// 是否登录
if (zerjie_is_logged_in()) {
    // 已登录
}

// 获取当前用户(未登录返回 null)
$user = zerjie_get_current_user();

登录 / 登出

// 登录:成功返回 true,失败返回 false
$success = zerjie_login($username, $password);

// 失败时读取具体原因
if (!$success) {
    $reason = $GLOBALS['zerjie_login_error'];
    // 'user_not_found'   账号不存在
    // 'invalid_password' 密码错误
    // 'account_pending'  账号待激活
    // 'account_banned'   账号被封禁
}

// 登出
zerjie_logout();

角色

角色说明
super_admin超级管理员,拥有所有权限(强制)
admin管理员,权限由 role_caps 配置
user普通用户,权限由 role_caps 配置

角色常量:ROLE_GUEST、ROLE_USER、ROLE_ADMIN、ROLE_SUPER_ADMIN。

权限检查

if (zerjie_current_user_can('manage_options')) {
    // 有权限
}

// 常用权限名:
// read, view_users, manage_users,
// view_settings, manage_settings,
// manage_themes, manage_plugins, manage_widgets,
// manage_taxonomy, manage_nav_menu,
// view_cli, manage_cli, manage_options

登录失败限制

// 检查是否被锁
$check = zerjie_login_attempt_check($identifier);
// → ['locked' => bool, 'remaining' => int, 'count' => int, 'max' => int]

// 记录一次失败
zerjie_login_attempt_record($identifier);

// 登录成功时重置计数
zerjie_login_attempt_reset($identifier);

用户注册

推荐用统一 API zerjie_register_user(),会自动读取后台的注册开关、默认角色、IP 限制等配置。

最简用法

$result = zerjie_register_user($username, $password, $email);

if ($result['success']) {
    $userId = $result['user_id'];
    $status = $result['status'];   // 'active' | 'pending'
    $meta   = $result['meta'];

    if (!empty($meta['auto_logged_in'])) {
        // 注册后已自动登录
    } elseif (!empty($meta['activation_email_sent'])) {
        // 已发送激活邮件
    } elseif (!empty($meta['requires_activation'])) {
        // 等待管理员审核
    }
} else {
    $errors = $result['errors'];
}

完整参数

$result = zerjie_register_user($username, $password, $email, [
    'role'            => 'user',       // 覆盖默认角色
    'status'          => 'active',     // 覆盖默认状态
    'display_name'    => 'Alice',
    'skip_validation' => false,
    'allow_open'      => true,
]);

激活流程

// 生成激活令牌(24 小时有效)
$token = zerjie_generate_activation_token($userId, 86400);

// 构建激活链接
$link = zerjie_build_activation_link($token);

// 发送激活邮件
zerjie_send_activation_email($userId, $username, $email);

// 用户点击后:
$result = zerjie_activate_user_by_token($token);
if ($result['success']) {
    // 激活成功
} else {
    echo $result['error'];
}

会话与 Flash

会话操作

zerjie_session_set('user_pref', 'dark');
$pref = zerjie_session_get('user_pref', 'light');
zerjie_session_has('user_pref');
zerjie_session_delete('user_pref');
zerjie_session_destroy();

Flash 消息(一次性)

flash_set('message', '操作成功');
flash_success('保存成功');
flash_error('保存失败');

// 读取(读取后立即删除)
$msg = flash_get('message');

路由与 URL

add_action('zerjie_ready', function () {
    global $zerjie_router;

    $zerjie_router->get('/about', function () { echo 'About'; });
    $zerjie_router->get('/post/{id:\d+}', function ($id) { echo "Post #{$id}"; });
    $zerjie_router->post('/contact', function () { /* ... */ });
    $zerjie_router->any('/api/data', function () { /* ... */ });

    // 分组
    $zerjie_router->group('/api/v1', function ($router) {
        $router->get('/users', function () { /* ... */ });
    });
});

命名路由 + URL 生成

$zerjie_router->get('/post/{id}', function ($id) { /* ... */ })->name('post');
$url = route('post', ['id' => 123]);   // → /post/123

Request 对象注入

use Zerjie\Http\Request;

$zerjie_router->post('/submit', function (Request $req) {
    $name = $req->input('name');
    $ua   = $req->header('User-Agent');
    $ip   = $req->ip();
});

缓存

// 写入(TTL 秒)
cache()->set('homepage_data', $data, 3600);

// 读取
$data = cache()->get('homepage_data');

// 判断存在
if (cache()->has('homepage_data')) { /* ... */ }

// 删除
cache()->delete('homepage_data');

// 清空全部
cache()->clear();

remember 模式

$expensive = cache()->remember('expensive_key', function () {
    return expensive_computation();
}, 3600);

多驱动

驱动说明适用场景
file文件缓存(默认)单机、共享主机
memory内存缓存(请求周期内)单次请求内的重复计算
redisRedis 缓存多机集群、高并发

日志

logger()->info('用户登录成功', ['user_id' => 5]);
logger()->warning('磁盘空间不足');
logger()->error('数据库连接失败', [
    'message' => $e->getMessage(),
    'file'    => $e->getFile(),
    'line'    => $e->getLine(),
]);

所有日志级别

方法级别
debug调试信息
info常规信息
notice值得注意
warning警告
error错误
critical严重错误
alert必须立即处理
emergency系统不可用

默认输出到 storage/logs/YYYY-MM-DD.log,自动保留最近 30 个日志文件。

邮件

基于 SMTP 发送。后台 → 系统 → SMTP 页面配置发信参数。

$result = zerjie_send_mail(
    'user@example.com',
    '欢迎加入',
    '这是邮件的正文内容'
);

if ($result['success']) {
    echo '发送成功';
} else {
    echo '发送失败:' . $result['message'];
}

HTML 邮件 + 抄送

$result = zerjie_send_mail(
    ['to1@example.com', 'to2@example.com'],
    '每周报告',
    '<h1>本周数据</h1>',
    [
        'is_html'  => true,
        'cc'       => ['cc@example.com'],
        'bcc'      => ['bcc@example.com'],
        'reply_to' => 'reply@example.com',
    ]
);

SMTP 配置项

配置 key说明默认
smtp_hostSMTP 服务器地址''
smtp_port端口465
smtp_encryptionssl / tls / nonessl
smtp_auth是否启用认证'1'
smtp_usernameSMTP 用户名''
smtp_passwordSMTP 密码''
from_email发件人邮箱''
from_name发件人名称'Zerjie'

队列

基于文件系统的轻量队列,适合异步任务(发邮件、生成缩略图、同步数据)。

定义任务

namespace MyPlugin\Jobs;

use Zerjie\Queue\Job;

class SendWelcomeEmail extends Job {
    public function handle($payload) {
        $userId = (int) ($payload['user_id'] ?? 0);
        $email  = (string) ($payload['email'] ?? '');

        zerjie_send_mail($email, '欢迎', '欢迎加入!');

        return true;   // false = 失败重试
    }
}

推送任务

use Zerjie\Queue\Queue;

$queue = new Queue('default');
$queue->push('MyPlugin\Jobs\SendWelcomeEmail', ['user_id' => 123, 'email' => 'a@b.com']);
$queue->later(60, 'MyPlugin\Jobs\SendWelcomeEmail', ['user_id' => 123]);

处理任务

# 处理 1 个任务后退出
php console.php queue:work

# 处理 100 个任务
php console.php queue:work default 100

# 查看队列长度
php console.php queue:size

队列目录结构

storage/queue/{queueName}/
├── *.job                 待处理任务
├── delayed/              延迟任务
├── processing/           处理中任务
└── failed/               失败归档

多语言

// 返回翻译文本
$text = __('Hello World');

// 带占位符
$text = __('Welcome, {name}!', ['name' => 'Alice']);

// 直接输出
_e('Save Settings');

// 设置 / 获取当前语言
set_language('zh-TW');
$locale = get_language();

语言文件位置

  1. adminbackend/languages/{locale}.php(系统语言包)
  2. content/languages/{locale}.php(用户自定义,优先级更高)

可以通过 filter 追加自定义目录:

add_filter('zerjie_language_paths', function ($paths) {
    $paths[] = ZERJIE_ROOT . '/my-lang';
    return $paths;
});

语言文件格式

<?php
// content/languages/zh-CN.php
return [
    'Hello World'      => '你好,世界',
    'Welcome, {name}!' => '欢迎,{name}!',
];

语言检测优先级

  1. $_SESSION['user_language'](用户在后台切换过)
  2. 浏览器 Accept-Language 头(匹配到存在的语言包)
  3. 系统默认语言(config/system.php 的 default_language)

CSRF 防护

表单中输出隐藏字段

<form method="post">
    <?= csrf_field() ?>
    <input type="text" name="title">
    <button>提交</button>
</form>

服务端校验

// 自动从 POST _csrf 字段或 X-CSRF-Token 头提取
if (!csrf_check()) {
    die('CSRF 校验失败');
}

AJAX 请求头

fetch('/api/endpoint', {
    method: 'POST',
    headers: {
        'X-CSRF-Token': window.ZJ.cfg.csrf,
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ ... }),
});

CSRF 类 API

方法说明
Csrf::getToken()获取当前令牌(无则生成)
Csrf::generateToken()强制生成新令牌
Csrf::verifyToken($token)校验指定令牌
Csrf::clearToken()删除当前令牌
Csrf::rotate()清空 + 生成新令牌
Csrf::hiddenField()输出隐藏字段 HTML
Csrf::metaField()输出 <meta name="csrf-token">
登录时自动轮换:zerjie_login() 成功后会调用 Csrf::rotate(),防止会话固定攻击。

XSS 防护

输出转义(最常用)

<?= Helper::e($userInput) ?>
<?= zerjie_escape_html($html) ?>

富文本过滤

// 保留安全的 HTML 标签
$clean = zerjie_xss_filter($html, ['p', 'br', 'strong', 'a']);

zerjie_xss_filter() 使用 DOMDocument 逐节点清理:

  • 白名单外的标签直接移除
  • 白名单外的属性直接移除
  • URL 属性(href / src)检查 scheme(仅允许 http / https / mailto / tel / ftp)
  • data: 仅允许 image/gif / image/png / image/jpeg / image/webp
  • target="_blank" 自动追加 rel="noopener noreferrer"
  • style 里的 expression() / javascript: / @import 等全部剔除

输入验证与清理

通用清理

// 去除首尾空白、删除 HTML 标签
$clean = zerjie_sanitize_input($_POST['comment']);

// 数组会自动递归清理
$data = zerjie_sanitize_input($_POST);

验证函数

函数说明返回
zerjie_validate_email($email)验证邮箱bool
zerjie_validate_url($url)验证 URLbool
zerjie_validate_int($value)验证整数bool
Sanitizer::validateFloat($v)验证浮点数bool
Sanitizer::validateBool($v)验证布尔bool / null
Sanitizer::validatePhone($p)验证中国大陆手机号bool
Sanitizer::validateIdCard($id)验证中国大陆身份证bool

文件上传安全

校验上传文件

$result = zerjie_validate_upload(
    $_FILES['file'],
    ['jpg', 'png', 'gif'],
    ['image/jpeg', 'image/png', 'image/gif'],
    5 * 1024 * 1024
);

if (!$result['valid']) {
    die($result['error']);
}

UploadGuard::validate() 会依次检查:PHP 上传错误码 → 文件大小 → 扩展名白名单 → ZIP 安全检查(防压缩炸弹)→ MIME 类型匹配 → 图片文件额外用 getimagesize() 验证。

生成安全文件名

$safeName = zerjie_safe_filename($_FILES['file']['name'], 'upload_');
// → upload_66f3a1b2c4d5e.jpg

ZIP 安全解压

try {
    zerjie_safe_extract_zip('/path/to/file.zip', '/path/to/dest');
} catch (Exception $e) {
    die($e->getMessage());
}

zerjie_safe_extract_zip() 含四道防线:

  1. 路径规范化:统一分隔符、去首尾斜杠、去 ./
  2. 禁止路径遍历:检测 ../ 片段
  3. 禁止符号链接:读 ZIP 外部属性,检测 symlink
  4. 目标目录前缀校验:解压后每个文件必须在目标目录内

防火墙与限流

IP 黑名单

if (zerjie_is_ip_blocked()) {
    die('您的 IP 已被封禁');
}

zerjie_block_ip('1.2.3.4');
zerjie_unblock_ip('1.2.3.4');

频率限制

// 60 秒内最多 60 次
if (!zerjie_rate_limit(null, 60, 60)) {
    http_response_code(429);
    header('Retry-After: 60');
    die('请求过于频繁');
}

// 自定义 key
if (!zerjie_rate_limit('login:' . $ip, 5, 300)) {
    // 300 秒内同一 IP 最多登录 5 次
}

驱动优先级

  1. APCu(如果启用):内存计数,最快
  2. 文件锁(兜底):storage/cache/ratelimit/{key}.lock

防御响应系统

完整的分级防御系统,由 Zerjie\Security\Defense 提供。

自动启用

内核在 zerjie_ready 之后自动调用 Defense::enforce(),无需手动启用。

核心方法

方法说明
Defense::getStatus()返回当前防御状态
Defense::banIp($ip, $forcePermanent)封禁 IP
Defense::unbanIp($ip, $resetCount)解封 IP
Defense::listBannedIps()列出所有生效的封禁
Defense::isBanned($ip)检查 IP 是否被封
Defense::clear()清除全站防御等级
Defense::setLevel($level, $reason, $duration)手动设置防御等级

分级说明

等级默认阈值作用范围响应
L160s / 5000 次全站仅记录
L260s / 10000 次全站仅记录
L360s / 50000 次写操作503,持续 60s
L4300s / 100000 次敏感路径503,持续 300s
L5300s / 500000 次全站503,需手动解除

敏感路径扫描

内置一批正则匹配常见攻击路径(.env、.git、wp-admin、phpmyadmin、*.sql、AI 工具配置等)。5 分钟内同一 IP 命中 N 次(默认 5 次)自动封禁。

add_filter('zerjie_defense_suspicious_patterns', function ($patterns) {
    $patterns[] = '#/my-secret-path#i';
    return $patterns;
});

add_filter('zerjie_defense_scan_threshold', function () {
    return 3;
});

数据表

  • {prefix}defense_slots:全站每分钟请求数
  • {prefix}defense_ip_slots:每 IP 每分钟请求数
  • {prefix}defense_ip_bans:IP 封禁记录
  • {prefix}defense_scan_log:敏感路径扫描日志

完整性守卫

Zerjie\Security\IntegrityGuard 周期性比对核心文件与官方清单,发现被篡改的文件会自动从官方服务器下载原始版本覆盖。

启用 / 关闭

# 启用(会二次确认)
php console.php integrity:on

# 查看状态
php console.php integrity:status

# 手动触发检查
php console.php integrity:check

# 关闭
php console.php integrity:off

官方清单的排除项

清单不会包含以下路径(防止覆盖站点私有数据):

install/                安装后会被删除
config/                 每站的数据库配置不同
storage/                运行时数据
content/                主题、插件、小工具、上传文件
templates/lock-pages/   用户可上传自定义锁页模板
admin.php               站点独有,安装时生成,用户可重命名
⚠️ 安全提示:启用后系统会周期性从官方拉取原始文件并覆盖本地核心文件。如果你自己修改过核心文件,请勿开启此功能。

本地完整性检查

安装时生成的 storage/manifest.json 会在每次请求开始时用于比对核心文件。任一文件被修改或缺失 → 立即返回 503。

# 重新生成清单
php console.php security:manifest

# 检查核心文件是否完整
php console.php security:check

检查更新

Zerjie\Update\UpdateChecker 从官方服务器检查是否有新版本。

php console.php update:check
use Zerjie\Update\UpdateChecker;

// 检查(带缓存,默认 1 小时)
$info = UpdateChecker::check();

// 强制检查(忽略缓存)
$info = UpdateChecker::check(true);

// 快捷判断
if (UpdateChecker::hasUpdate()) {
    // 有新版本
}

// 清理缓存
UpdateChecker::clearCache();

安全措施

  • URL 必须在可信 base 下(防止 SSRF)
  • HTTPS 强制
  • 不跟随重定向
  • SSL 证书验证

下载与安装

# 下载最新更新包(不安装)
php console.php update:download

# 下载 + 安装(一步到位)
php console.php update:apply
use Zerjie\Update\UpdateChecker;
use Zerjie\Update\Updater;

// 1. 检查
$info = UpdateChecker::check(true);
if ($info['status'] !== 'update_available') {
    die('无可用更新');
}

// 2. 下载
$dl = Updater::download($info);

// 3. 解压 + 校验
$prep = Updater::prepare($dl['file']);

// 4. 应用
$apply = Updater::apply($prep['dir'], $prep['files'], '1.2.0');

允许更新的路径

core/           核心
adminbackend/   后台
assets/         系统级静态资源
templates/      兜底模板
index.php
console.php
favicon.ico
favicon.png

更新包不能修改:

admin.php               站点独有
templates/lock-pages/   用户自定义
config/                 站点配置
storage/                运行时数据
content/                主题、插件、小工具

回滚

# 列出所有备份
php console.php update:backups

# 回滚到指定备份
php console.php update:rollback 20260115_143022
use Zerjie\Update\Updater;

$list = Updater::listBackups();
$result = Updater::rollback('20260115_143022');

CLI 命令

通过 php console.php <command> 在服务器终端执行。

命令说明
用户管理
user:list列出所有用户
user:add <用户名> <密码> <邮箱> [角色]添加用户
user:delete <ID>删除用户
user:password <ID或用户名> <新密码> [--force]改密码
user:promote <ID或用户名> <角色> [--force]改角色
user:count统计各角色用户数
主题
theme:list / theme:activate / theme:info主题管理
插件
plugin:list / plugin:activate / plugin:deactivate / plugin:info插件管理
缓存 / 日志
cache:clear / cache:stats缓存管理
log:clear / log:tail / log:list日志管理
数据库
db:list-tables / db:table-info / db:size / db:optimize / db:backup数据库管理
migrate / migrate:rollback / migrate:reset迁移
系统
system:info / system:health / system:routes / system:env / system:time / system:debug / system:clear-temp系统信息与诊断
调试模式
debug:on / debug:off / debug:status / debug:toggle调试模式开关
队列
queue:work [name] [max] / queue:size队列管理
安全
security:manifest / security:check完整性清单
defense:status / defense:clear / defense:cleanup防御系统
integrity:on / integrity:off / integrity:status / integrity:check完整性守卫
更新
update:check / update:download / update:apply / update:backups / update:rollback更新系统

数据表结构

系统表都以 {prefix} 为前缀(默认 wp_),安装时自定义。

表名用途
{prefix}users用户账户
{prefix}options系统配置(键值对)
{prefix}logs数据库日志
{prefix}migrations迁移记录
{prefix}taxonomies分类
{prefix}term_relationships内容-分类关联
{prefix}menus / {prefix}menu_items导航菜单
{prefix}invite_codes邀请码(站点锁)
{prefix}register_log / {prefix}login_attempts注册与登录失败记录
{prefix}defense_*防御系统 4 张表

钩子速查表

内核钩子

钩子类型说明
zerjie_readyAction内核初始化完成(所有扩展入口)
zerjie_admin_menuFilter后台菜单注册
zerjie_admin_headAction后台 <head> 输出
zerjie_admin_footerAction后台 </body> 前输出
zerjie_admin_topbarAction顶栏输出
zerjie_admin_footer_before / zerjie_admin_footer_afterAction页脚前后
zerjie_admin_footer_textFilter页脚文字
zerjie_admin_page_content_{action}Filter替换某个后台页面内容
zerjie_admin_layout_file / zerjie_admin_login_fileFilter替换布局 / 登录页
zerjie_theme_template_fileFilter主题模板路径注册
zerjie_widgets / zerjie_widget_areasFilter小工具 / 区域注册
zerjie_settings_fieldsFilter设置字段注册
zerjie_language_pathsFilter多语言包路径追加
zerjie_dashboard_widgetsFilter仪表盘小部件

SEO 钩子

钩子类型说明
zerjie_seo_page_typeFilter覆盖页面类型判断
zerjie_seo_page_titleFilter覆盖页面标题
zerjie_seo_title_fullFilter覆盖最终 title
zerjie_seo_meta_description_textFilter覆盖 meta description
zerjie_seo_canonical_urlFilter覆盖 canonical URL
zerjie_seo_robotsFilter覆盖 robots meta
zerjie_seo_open_graph_tagsFilter覆盖 OG 标签
zerjie_seo_twitter_tagsFilter覆盖 Twitter Card
zerjie_seo_jsonldFilter追加 JSON-LD
zerjie_seo_head_outputFilter整体覆盖 SEO 输出
zerjie_seo_robots_txt_contentFilter覆盖 robots.txt 内容
zerjie_seo_sitemap_urlsFilter追加 sitemap 条目
zerjie_seo_sitemap_xmlFilter覆盖最终 sitemap XML

注册相关

钩子类型说明
zerjie_registration_openFilter是否开放注册
zerjie_default_registration_role / zerjie_default_registration_statusFilter默认角色 / 状态
zerjie_username_available / zerjie_email_availableFilter用户名 / 邮箱可用性
zerjie_username_min_length / zerjie_password_min_lengthFilter长度限制
zerjie_password_strengthFilter密码强度校验
zerjie_register_args / zerjie_register_validation / zerjie_register_user_data / zerjie_register_resultFilter注册参数 / 校验 / 数据 / 结果
zerjie_before_register / zerjie_after_register / zerjie_user_activated / zerjie_user_pending / zerjie_registration_failedAction注册生命周期

防御系统

钩子类型说明
zerjie_defense_suspicious_patternsFilter敏感路径正则列表
zerjie_defense_scan_thresholdFilter扫描命中封禁阈值
zerjie_defense_suspicious_requestAction命中敏感路径时广播

常见问题

Q1:修改主题文件后不生效?

可能是浏览器缓存了旧 CSS / JS。在引用资源时加版本号强制刷新:

<link rel="stylesheet" href="/content/themes/my-theme/assets/css/style.css?v=<?= filemtime(__DIR__ . '/assets/css/style.css') ?>">

Q2:后台入口忘了叫什么?

查看 config/system.php 中的 admin_entry 字段;或执行:

php console.php system:info

Q3:用户登录状态频繁失效?

可能是 session_token 校验失败。原因:

  • 其他设备登录了同一账号(会强制下线)
  • 密码被修改(会重置 session_token)
  • 会话超时(默认 24 小时)

Q4:如何让插件覆盖后台菜单的默认项?

add_filter('zerjie_admin_menu', function ($menus) {
    foreach ($menus as &$m) {
        if (($m['slug'] ?? '') === 'dashboard') {
            $m['title'] = '我的仪表盘';
        }
    }
    return $menus;
}, 20);

Q5:如何查看日志?

# 查看最新 50 行
php console.php log:tail 50

# 或直接读文件
tail -f storage/logs/$(date +%Y-%m-%d).log

Q6:debug 模式下调试代码

php console.php debug:on

// 代码中
dump($variable);
dd($variable);

Q7:升级数据库表结构

// 在 database/migrations/ 下新建 20260101_add_column.php
<?php
return [
    'up' => function ($db, $prefix) {
        $db->exec("ALTER TABLE `{$prefix}users` ADD COLUMN `nickname` VARCHAR(60)");
    },
    'down' => function ($db, $prefix) {
        $db->exec("ALTER TABLE `{$prefix}users` DROP COLUMN `nickname`");
    },
];

// 执行
php console.php migrate

Q8:CSP 拦截了内联脚本?

Zerjie 的 CSP 策略是 script-src 'self',禁止内联脚本。解决方案:

  1. 把脚本写到独立 .js 文件中
  2. 不要用 <script>...代码...</script> 内联
  3. 不要用 onclick="..." 等内联事件,改用事件委托

Q9:主题首页显示"Template index does not exist"?

主题没有注册 zerjie_theme_template_file filter,或没有注册 / 路由。两种方式任选:

// 方式 1:filter
add_filter('zerjie_theme_template_file', function ($file, $template, $theme) {
    if ($theme !== 'my-theme') return $file;
    $path = __DIR__ . '/templates/' . $template . '.php';
    return file_exists($path) ? $path : $file;
}, 10, 3);

// 方式 2:路由(推荐)
add_action('zerjie_ready', function () {
    global $zerjie_router;
    $zerjie_router->get('/', function () {
        require __DIR__ . '/templates/index.php';
        exit;
    });
});

Q10:小工具拖拽到区域后前台不显示?

  1. 主题模板是否调用了 the_widgets('区域名')
  2. 区域名是否与后台拖拽时的一致
  3. 小工具的 sidebar 参数默认值是否匹配(只是默认,最终由拖拽决定)

Q11:开启完整性守卫后站点 503?

可能是清单中某个核心文件与你本地的 SHA-256 不一致。检查步骤:

  1. 查看 storage/logs/security.log 找出被标记的文件
  2. 如果你故意修改过核心文件,应该关闭完整性守卫:php console.php integrity:off
  3. 如果是意外篡改,用 php console.php security:check 定位
  4. 需要临时放行,重新生成清单:php console.php security:manifest

Q12:如何修改防御系统的敏感路径规则?

add_filter('zerjie_defense_suspicious_patterns', function ($patterns) {
    $patterns[] = '#/my-secret-url#i';

    $patterns = array_filter($patterns, function ($p) {
        return strpos($p, '.env') === false;
    });

    return array_values($patterns);
});

Q13:邮件发送失败怎么排查?

  1. 后台 → 系统 → SMTP 页面,检查配置是否完整(host / username / password / from_email)
  2. 用「发送测试」按钮验证 SMTP 连接
  3. 查看 storage/logs/YYYY-MM-DD.log,搜索 mail
  4. 常见问题:端口被云服务商封锁(改用 587 + TLS)、密码用的是授权码而非登录密码

Q14:如何切换缓存驱动到 Redis?

在 core/zerjie.php 里修改初始化代码:

// 原代码
$cacheManager = new Zerjie\Cache\CacheManager('file');

// 改为
$cacheManager = new Zerjie\Cache\CacheManager('redis');

Q15:主题已经在 <head> 里调用了 zerjie_seo_head(),但 title 还是不对?

检查三点:

  1. 页面是否设置了 $GLOBALS['zerjie_seo_title'] 或 $GLOBALS['pageTitle']
  2. 是否需要 add_filter('zerjie_seo_title_full', ...) 完全覆盖
  3. 后台「系统设置 → 站点信息」里的 title_separator / page_title_separator 是否正确

Q16:robots.txt 里没有 Sitemap 行?

  1. 检查后台「系统设置 → SEO · 抓取配置 → 生成 /sitemap.xml」是否开启(seo_sitemap_enabled = 1)
  2. 如果手动编辑过 robots.txt 内容并已包含 Sitemap: 行,系统不再自动追加
  3. 直接访问 /robots.txt 查看实际输出