跳转到正文

全栈区块

Blockstudio让你可以在一个区块文件夹中构建完整应用。单个目录可以包含UI、服务器逻辑、数据模型、定时任务,甚至数据本身。

本指南将构建两个实际应用来展示这一模式:一个按用户隔离的待办应用,以及一个公开的新闻邮件订阅表单。文件结构相同,访问模型不同。

以下示例使用数组语法,因为它最简洁;不过,这三个PHP接口也都提供PHP原生替代方案:

  • db.php可以使用Blockstudio\\Db\\Schema和Blockstudio\\Db\\Field
  • rpc.php可以返回包含#[Rpc]方法的对象
  • cron.php可以返回包含#[Cron]方法的对象

待办应用

一个按用户隔离的任务管理器。每位已登录用户只能看到自己的待办事项。它使用userScoped: true自动隔离用户,使用SQLite实现可移植存储,使用bs.mutate()进行乐观更新,并通过实时轮询自动显示其他标签页中的更改。

文件结构

代码
blockstudio/
  todo/
    block.json
    index.php
    script.inline.js
    style.css
    db.php
    rpc.php
    cron.php

区块定义

JSON
{
  "$schema": "https://blockstudio.dev/schema/block",
  "name": "my-theme/todo",
  "title": "Todo App",
  "category": "widgets",
  "icon": "editor-ul",
  "supports": {
    "interactivity": true
  },
  "blockstudio": {
    "interactivity": {
      "enqueue": true
    }
  }
}

supports.interactivity启用WordPress的指令处理(适用于data-wp-each、data-wp-bind等的 SSR)。interactivity.enqueue会在前端加载@wordpress/interactivity模块。

数据模型

userScoped: true会自动添加user_id列,在创建时设置该列,并将所有查询过滤为当前用户的数据。realtime会启用自动轮询,以便无需刷新页面即可显示其他标签页或设备中的更改。

PHP
<?php
return [
    'storage'    => 'sqlite',
    'userScoped' => true,
    'realtime'   => [
        'key'      => 'todos',
        'interval' => 3000,
    ],
    'capability' => [
        'create' => true,
        'read'   => true,
        'update' => true,
        'delete' => true,
    ],
    'fields' => [
        'text' => [
            'type'      => 'string',
            'required'  => true,
            'minLength' => 1,
            'maxLength' => 500,
        ],
        'done' => [
            'type'    => 'boolean',
            'default' => false,
        ],
    ],
];

SQLite存储表示数据库文件位于todo/db/default.sqlite。将区块文件夹复制到另一个网站,数据也会随之迁移。

realtime配置会让客户端每 3 秒使用轻量级哈希比较轮询一次更改。数据发生变化时,state.todos会更新,UI也会自动重新渲染。

自定义服务器逻辑

由于userScoped会自动过滤为当前用户的数据,内置的bs.db().list()已经只返回当前用户的记录。RPC仅在 CRUD 以外的操作中需要,例如切换状态和批量清除。

PHP
<?php
use Blockstudio\Db;

return [
    'toggle' => [
        'callback' => function (array $params) {
            $id = (int) ($params['id'] ?? 0);

            if (!$id) {
                return new \WP_Error('missing_id', 'ID is required.', ['status' => 400]);
            }

            $db   = Db::get('my-theme/todo');
            $todo = $db->get_record($id);

            if (!$todo) {
                return new \WP_Error('not_found', 'Not found.', ['status' => 404]);
            }

            return $db->update($id, ['done' => !$todo['done']]);
        },
        'public'  => true,
        'methods' => ['POST'],
    ],
    'clear_done' => [
        'callback' => function () {
            $db    = Db::get('my-theme/todo');
            $todos = $db->list();
            $count = 0;

            foreach ($todos as $todo) {
                if (!empty($todo['done'])) {
                    $db->delete((int) $todo['id']);
                    ++$count;
                }
            }

            return ['deleted' => $count];
        },
        'public'  => true,
        'methods' => ['POST'],
    ],
];

定时清理

旧的已完成待办事项会自动清理。

PHP
<?php
use Blockstudio\Db;

return [
    'cleanup_old_todos' => [
        'schedule' => 'daily',
        'callback' => function () {
            $db    = Db::get('my-theme/todo');
            $todos = $db->list();

            foreach ($todos as $todo) {
                $is_done = $todo['done'];
                $is_old  = strtotime($todo['updated_at']) < strtotime('-30 days');

                if ($is_done && $is_old) {
                    $db->delete((int) $todo['id']);
                }
            }
        },
    ],
];

模板

PHP通过wp_interactivity_state()在服务器端加载初始待办事项,为 SSR 指令处理和客户端水合提供数据。每个实例的UI状态(例如输入框的值)放在data-wp-context中。

PHP
<?php
$db         = \Blockstudio\Db::get('my-theme/todo');
$todos      = $db ? $db->list() : [];
$items_left = count(array_filter($todos, fn($t) => empty($t['done'])));

wp_interactivity_state('my-theme/todo', [
    'todos'     => array_values($todos),
    'hasTodos'  => !empty($todos),
    'hasDone'   => count($todos) !== $items_left,
    'itemsLeft' => $items_left . ($items_left === 1 ? ' item left' : ' items left'),
]);
?>
<div
    data-wp-interactive="my-theme/todo"
    data-wp-context='<?php echo esc_attr(wp_json_encode(['newText' => ''])); ?>'
    useBlockProps
    class="todo-app"
>
    <h2>Todos</h2>

    <div class="todo-input">
        <input
            type="text"
            placeholder="What needs to be done?"
            data-wp-bind--value="context.newText"
            data-wp-on--input="my-theme/todo::actions.updateNewText"
            data-wp-on--keydown="my-theme/todo::actions.handleKeyDown"
        />
        <button
            data-wp-on--click="my-theme/todo::actions.addTodo"
            data-wp-bind--disabled="!state.canAdd"
        >Add</button>
    </div>

    <ul class="todo-list">
        <template data-wp-each--todo="state.todos" data-wp-each-key="context.todo.id">
            <li>
                <label>
                    <input
                        type="checkbox"
                        data-wp-bind--checked="context.todo.done"
                        data-wp-on--change="actions.toggleTodo"
                    />
                    <span
                        data-wp-text="context.todo.text"
                        data-wp-class--done="context.todo.done"
                    ></span>
                </label>
                <button
                    class="todo-delete"
                    data-wp-on--click="actions.deleteTodo"
                >&times;</button>
            </li>
        </template>
    </ul>

    <div class="todo-footer" data-wp-bind--hidden="!state.hasTodos">
        <span data-wp-text="state.itemsLeft"></span>
        <button
            data-wp-on--click="my-theme/todo::actions.clearDone"
            data-wp-bind--hidden="!state.hasDone"
        >Clear done</button>
    </div>
</div>

关键模式:

  • wp_interactivity_state()用于来自服务器的数据(待办事项、计数)
  • data-wp-context用于临时的UI状态(输入文本)
  • data-wp-each--todo为每次迭代中的项目提供命名上下文(context.todo)
  • state.*引用全局存储,context.*引用每个实例的数据

客户端逻辑

bs.mutate()负责所有写入操作,并提供乐观更新和自动回滚。UI会立即更新;如果服务器调用被拒绝,状态就会恢复。验证或权限错误会以错误正文的形式返回,而不是触发拒绝,详见Mutate。

JavaScript
import { store, getContext } from '@wordpress/interactivity';

const { state } = store('my-theme/todo', {
    state: {
        get canAdd() {
            return getContext().newText.trim() !== '';
        },
        get hasTodos() {
            return state.todos.length > 0;
        },
        get hasDone() {
            return state.todos.some(t => t.done);
        },
        get itemsLeft() {
            const count = state.todos.filter(t => !t.done).length;
            return count + (count === 1 ? ' item left' : ' items left');
        },
    },
    actions: {
        updateNewText(event) {
            getContext().newText = event.target.value;
        },
        handleKeyDown(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                store('my-theme/todo').actions.addTodo();
            }
        },
        *addTodo() {
            const ctx = getContext();
            const text = ctx.newText.trim();
            if (!text) return;
            ctx.newText = '';

            yield bs.mutate({
                fn: () => bs.db('my-theme/todo').create({ text, done: false }),
                state, key: 'todos', action: 'create',
                optimistic: { text, done: false },
            });
        },
        *toggleTodo() {
            const todo = getContext().todo;

            yield bs.mutate({
                fn: () => bs.fn('toggle', { id: todo.id }, 'my-theme/todo'),
                state, key: 'todos', action: 'update', id: todo.id,
                optimistic: { ...todo, done: !todo.done },
            });
        },
        *deleteTodo() {
            const todo = getContext().todo;

            yield bs.mutate({
                fn: () => bs.db('my-theme/todo').delete(todo.id),
                state, key: 'todos', action: 'delete', id: todo.id,
            });
        },
        *clearDone() {
            yield bs.mutate({
                fn: () => bs.fn('clear_done', {}, 'my-theme/todo'),
                before() {
                    const snap = state.todos.slice();
                    state.todos = state.todos.filter(t => !t.done);
                    return snap;
                },
                onError(err, snap) { state.todos = snap; },
                invalidate: 'todos',
            });
        },
    },
});

关键模式:

  • bs.mutate()自动模式适用于创建/更新/删除:传入state、key、action和optimistic数据。UI会立即更新,服务器调用在后台进行,失败时状态会回滚。
  • bs.mutate()手动模式适用于clearDone:before()会创建快照并应用更改,onError()会从快照恢复。
  • 生成器函数(*addTodo)配合yield,用于交互性API中的异步操作。
  • bs.db()用于直接 CRUD,bs.fn()用于自定义服务器函数。

样式

CSS
.todo-app {
    max-width: 500px;
    margin: 0 auto;
    font-family: system-ui, sans-serif;
}

.todo-input {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
}

.todo-input input {
    flex: 1;
    padding: 0.5rem 0.75rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
}

.todo-input button {
    padding: 0.5rem 1rem;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 0.375rem;
    cursor: pointer;
}

.todo-list {
    list-style: none;
    padding: 0;
}

.todo-list li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.75rem 0;
    border-bottom: 1px solid #f3f4f6;
}

.todo-list label {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    flex: 1;
    cursor: pointer;
}

.todo-list .done {
    text-decoration: line-through;
    color: #9ca3af;
}

.todo-delete {
    background: none;
    border: none;
    color: #ef4444;
    font-size: 1.25rem;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.15s;
}

.todo-list li:hover .todo-delete {
    opacity: 1;
}

.todo-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 0;
    font-size: 0.875rem;
    color: #6b7280;
}

.todo-footer button {
    background: none;
    border: none;
    color: #6b7280;
    cursor: pointer;
    text-decoration: underline;
}

CLI

命令行
wp bs db list my-theme/todo
wp bs db create my-theme/todo --text="Buy milk" --user_id=1
wp bs cron run my-theme/todo cleanup_old_todos
wp bs rpc call my-theme/todo toggle --id=1

新闻邮件订阅

一个公开的订阅表单。任何人都可以订阅,只有管理员可以查看和管理订阅者。主要操作不需要userScoped,也不需要身份验证。生产环境使用MySQL表存储。

文件结构

代码
blockstudio/
  newsletter/
    block.json
    index.php
    style.css
    script.inline.js
    db.php
    rpc.php
    cron.php

区块定义

JSON
{
  "$schema": "https://blockstudio.dev/schema/block",
  "name": "my-theme/newsletter",
  "title": "Newsletter Signup",
  "category": "widgets",
  "icon": "email",
  "supports": {
    "interactivity": true
  },
  "blockstudio": {
    "interactivity": {
      "enqueue": true
    }
  }
}

数据模型

公开创建并提供 CSRF 保护。自定义验证会拦截一次性邮箱地址。读取和删除仅限管理员操作。

PHP
<?php
return [
    'storage'    => 'table',
    'capability' => [
        'create' => true,
        'read'   => 'manage_options',
        'update' => 'manage_options',
        'delete' => 'manage_options',
    ],
    'fields' => [
        'email' => [
            'type'     => 'string',
            'format'   => 'email',
            'required' => true,
            'validate' => function ($value) {
                $blocked = ['mailinator.com', 'tempmail.com', 'throwaway.email'];
                $domain  = substr($value, strpos($value, '@') + 1);
                if (in_array($domain, $blocked, true)) {
                    return 'Please use a permanent email address.';
                }
                return true;
            },
        ],
        'name' => [
            'type'      => 'string',
            'maxLength' => 100,
        ],
        'status' => [
            'type'    => 'string',
            'enum'    => ['active', 'unsubscribed'],
            'default' => 'active',
        ],
    ],
    'hooks' => [
        'after_create' => function ($params) {
            $name = $params['record']['name'];
            wp_mail(
                $params['record']['email'],
                'Welcome!',
                'Thanks for subscribing' . ($name ? ", $name" : '') . '.'
            );
        },
    ],
];

自定义逻辑

公开的取消订阅端点(可从电子邮件链接访问,无需登录)和仅限管理员访问的统计数据:

PHP
<?php
use Blockstudio\Db;

return [
    'unsubscribe' => [
        'callback' => function (array $params): array {
            $email = sanitize_email($params['email'] ?? '');
            $db    = Db::get('my-theme/newsletter');
            $subs  = $db->list(['email' => $email]);

            if (empty($subs)) {
                return ['error' => 'Email not found.'];
            }

            $db->update((int) $subs[0]['id'], ['status' => 'unsubscribed']);

            return ['success' => true];
        },
        'public' => true,
    ],
    'stats' => [
        'callback'   => function (array $params): array {
            $db = Db::get('my-theme/newsletter');
            return [
                'total'  => count($db->list()),
                'active' => count($db->list(['status' => 'active'])),
            ];
        },
        'capability' => 'manage_options',
    ],
];

定时清理

PHP
<?php
use Blockstudio\Db;

return [
    'cleanup' => [
        'schedule' => 'weekly',
        'callback' => function () {
            $db    = Db::get('my-theme/newsletter');
            $unsub = $db->list(['status' => 'unsubscribed']);

            foreach ($unsub as $row) {
                if (strtotime($row['updated_at']) < strtotime('-90 days')) {
                    $db->delete((int) $row['id']);
                }
            }
        },
    ],
];

模板

PHP
<?php
wp_interactivity_state('my-theme/newsletter', [
    'submitted' => false,
]);
?>
<div
    data-wp-interactive="my-theme/newsletter"
    data-wp-context='<?php echo esc_attr(wp_json_encode([
        'email'   => '',
        'name'    => '',
        'loading' => false,
        'error'   => '',
    ])); ?>'
    useBlockProps
    class="newsletter"
>
    <div data-wp-bind--hidden="state.submitted">
        <h3>Stay in the loop</h3>
        <div class="newsletter-form">
            <input
                type="text"
                placeholder="Name (optional)"
                data-wp-bind--value="context.name"
                data-wp-on--input="actions.setName"
            />
            <input
                type="email"
                placeholder="Email address"
                data-wp-bind--value="context.email"
                data-wp-on--input="actions.setEmail"
                data-wp-on--keydown="actions.handleKeydown"
            />
            <button
                data-wp-on--click="actions.subscribe"
                data-wp-bind--disabled="context.loading"
            >
                <span data-wp-text="context.loading ? 'Subscribing...' : 'Subscribe'"></span>
            </button>
        </div>
        <p data-wp-bind--hidden="!context.error" class="newsletter-error" data-wp-text="context.error"></p>
    </div>
    <div data-wp-bind--hidden="!state.submitted">
        <p class="newsletter-success">You're in! Check your email.</p>
    </div>
</div>

客户端逻辑

JavaScript
import { store, getContext } from '@wordpress/interactivity';

const { state } = store('my-theme/newsletter', {
    actions: {
        setName(event) {
            getContext().name = event.target.value;
        },
        setEmail(event) {
            getContext().email = event.target.value;
        },
        handleKeydown(event) {
            if (event.key === 'Enter') {
                store('my-theme/newsletter').actions.subscribe();
            }
        },
        *subscribe() {
            const ctx = getContext();
            const email = ctx.email.trim();
            if (!email) return;

            ctx.loading = true;
            ctx.error = '';

            const result = yield bs.db('my-theme/newsletter').create({
                email,
                name: ctx.name.trim(),
            });

            if (result.data?.errors) {
                ctx.error = Object.values(result.data.errors)[0][0];
                ctx.loading = false;
                return;
            }

            if (result.code) {
                ctx.error = result.message || 'Something went wrong.';
                ctx.loading = false;
                return;
            }

            state.submitted = true;
            ctx.loading = false;
        },
    },
});

样式

CSS
.newsletter {
    max-width: 480px;
    margin: 0 auto;
    padding: 2rem;
    text-align: center;
}

.newsletter h3 {
    margin: 0 0 1rem;
}

.newsletter-form {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.newsletter-form input {
    padding: 0.625rem 0.75rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 1rem;
}

.newsletter-form button {
    padding: 0.625rem 1rem;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 0.375rem;
    font-size: 1rem;
    cursor: pointer;
}

.newsletter-form button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.newsletter-error {
    color: #ef4444;
    font-size: 0.875rem;
    margin: 0.5rem 0 0;
}

.newsletter-success {
    color: #10b981;
    font-size: 1.125rem;
}

CLI

命令行
wp bs db list my-theme/newsletter --format=table
wp bs rpc call my-theme/newsletter stats
wp bs rpc call my-theme/newsletter unsubscribe --email=user@example.com
wp bs cron run my-theme/newsletter cleanup

并列对比

方面 待办应用 新闻邮件
身份验证模型 userScoped: true 公开创建,管理员读取
存储 SQLite(可移植) MySQL表(生产环境)
用户过滤 自动 不需要
CSRF 通过X-BS-Token 通过X-BS-Token
自定义RPC 切换状态、清除已完成项 取消订阅、统计数据
Cron 删除旧的已完成项 移除已取消订阅者
验证 长度限制 邮箱格式 + 域名屏蔽
实时更新 每 3 秒轮询 不需要
乐观UI bs.mutate()自动模式 直接bs.db().create()
状态 wp_interactivity_state() wp_interactivity_state() + 上下文

相同的模式,不同的访问模型。构建这些应用的组件完全相同:db.php用于数据模型,rpc.php用于业务逻辑,cron.php用于后台任务,index.php + script.inline.js用于UI,style.css用于外观。每个区块都是独立完整的应用。