定制 mzeahmed/wp-toolkit 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

mzeahmed/wp-toolkit

Composer 安装命令:

composer require mzeahmed/wp-toolkit

包简介

A PHP library with useful and reusable functions for WordPress.

README 文档

README

WP ToolKit is a PHP library that simplifies WordPress development by providing reusable classes to handle common operations :

  • AJAX requests
  • Database operations
  • and more...

Installation

composer require mzeahmed/wp-helpers

Then include Composer's autoloader in your project:

require_once 'vendor/autoload.php';

Features

  1. AJAX Requests
  2. Database Operations
  3. User Activity Monitoring
  4. Data Sanitization 5HTTP Client

Ajax Requests

The Ajax utility class simplifies working with AJAX in WordPress by providing methods for registering AJAX actions, validating requests, and sending JSON responses.

Features

  • Register AJAX Actions: Supports both authenticated (wp_ajax_) and public (wp_ajax_nopriv_) actions.
  • Send JSON Responses: Easily send success or error responses to the client.
  • Nonce Validation: Verifies nonces to ensure request authenticity.
  • Error Logging: Logs AJAX errors when WP_DEBUG is enabled.

Usage

1. Register an AJAX Action

use MzeAhmed\WpToolKit\Utils\Ajax;

Ajax::register('my_action', 'my_callback');

function my_callback()
{
    $data = [
        'message' => 'Action executed successfully!',
        'additional_info' => 'Extra data here'
    ];
    
    Ajax::sendJsonSuccess('Success!', $data);
}

2. Send JSON Responses

Use the sendJsonSuccess and sendJsonError methods to send standardized JSON responses:

Ajax::sendJsonSuccess('Success message', ['data' => 'value']);
Ajax::sendJsonError('Error message', ['error' => 'reason']);

3. Nonce Validation

Verify nonces to ensure that AJAX requests are secure:

Ajax::verifyNonce('nonce_field_name', 'action_name');

Need to define theses constants in the application: AJAX_SECURITY_NONCE_ACTION and AJAX_SECURITY_NONCE.

define('AJAX_SECURITY_NONCE_ACTION', 'my_action');
define('AJAX_SECURITY_NONCE', 'nonce_field_name');

And use wp_localize_script to pass the nonce to the client side.

wp_localize_script('your-script-handle', 'ajax_object', [
    'ajax_url' => admin_url('admin-ajax.php'),
    AJAX_SECURITY_NONCE => wp_create_nonce(AJAX_SECURITY_NONCE_ACTION),
]);

In the client side, you can use the nonce like this:

fetch(ajax_object.ajax_url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-WP-Nonce': ajax_object.nonce_field_name
    },
    body: new URLSearchParams({
        action: 'my_action',
        data: 'value'
    })
})

Database Operations

  • Abstract Repository: Base class for implementing the repository pattern with $wpdb.
  • Pagination Support: Easily paginate database results.
  • Bulk Operations: Perform bulk inserts, updates, and deletes.
  • Transaction Management: Start, commit, and rollback database transactions.
  • Error Logging: Automatically log and debug database errors.
  • Dynamic Query Building: Flexible support for building dynamic WHERE and JOIN clauses.

Usage

1. Implement a Repository

Create a repository class that extends the AbstractRepository class. For example:

namespace YourNamespace\Repositories;

use Mzeahmed\WpToolKit\Database\AbstractRepository;

class YourCustomRepository extends AbstractRepository
{
    public function __construct()
    {
        parent::__construct();
        $this->tableName = $this->wpdbPrefix . 'your_table_name';
    }

    public function findActiveItems(): array
    {
        return $this->findByCriteria(['status' => 'active']);
    }
}

2. Use the Repository

In your WordPress plugin or theme:

use YourNamespace\Repositories\YourCustomRepository;

$repository = new YourCustomRepository();
$activeItems = $repository->findActiveItems();

3. Bulk Operations

Perform bulk inserts, updates, or deletes:

// Bulk insert example
$repository->bulkInsert([
    ['column1' => 'value1', 'column2' => 'value2'],
    ['column1' => 'value3', 'column2' => 'value4'],
]);

// Bulk delete example
$repository->bulkDelete('id', [1, 2, 3]);

4. Transactions

Manage transactions to ensure data consistency:

$repository->beginTransaction();

try {
    $repository->insert(['column1' => 'value1']);
    $repository->update(['column2' => 'value2'], ['id' => 1]);
    $repository->commit();
} catch (\Exception $e) {
    $repository->rollback();
    error_log($e->getMessage());
}

User Activity Monitoring

The UserActivityMonitor class helps track user activity and determine online/offline status.

Features

  • Track User Activity: Monitor user activity and update the last seen timestamp.
  • Check Online Status: Determine if a user is online within a specified margin.
  • Retrieve Online Users: Get a list of all users currently online.
  • Identify Recently Offline Users: Retrieve users who recently went offline.

Usage

1. Update User Activity

use MzeAhmed\WpToolKit\UserActivityMonitor;

$monitor = new UserActivityMonitor();
$monitor->updateStatus($userId);

2. Check Online Status

$isOnline = $monitor->isUserOnline($userId);

if ($isOnline) {
    echo "User $userId is online.";
} else {
    echo "User $userId is offline.";
}

3. Retrieve Online Users

$onlineUsers = $monitor->getOnlineUsers();

foreach ($onlineUsers as $user) {
    echo "User $user->ID is online.";
}

4. Identify Recently Offline Users

$recentlyOfflineUsers = $monitor->getRecentlyOfflineUsers();

foreach ($recentlyOfflineUsers as $user) {
    echo "User $user->ID recently went offline.";
}

Data Sanitization

The Sanitizer class provides static methods to clean user input and ensure data safety in WordPress environments.

Features

  • ✅ Sanitize strings, emails, URLs, and textarea contents
  • 🔁 Sanitize arrays and nested arrays
  • 🎯 Apply custom sanitization rules per field

Supported Rules

Rule Description
text Uses sanitize_text_field()
email Uses sanitize_email()
url Uses esc_url_raw()
textarea Uses sanitize_textarea_field()

Usage

1. Sanitize a single value or array

use MzeAhmed\WpToolKit\Utils\Sanitizer;

$cleanText = Sanitizer::text(' John ');
// returns 'John'

$cleanEmailArray = Sanitizer::email(['  a@a.com ', 'b@b.com ']);
// returns ['a@a.com', 'b@b.com']

2. Recursively sanitize text values in nested arrays

$dirtyArray = [
    'name' => ' John ',
     'meta' => [
        'city' => ' Paris ',
        'desc' => " Hello\nWorld "
    ]
];

$clean = Sanitizer::recursiveText($raw);
// returns [
//   'name' => 'John',
//   'meta' => [
//     'city' => 'Paris',
//     'desc' => "Hello\nWorld"
//   ]
// ]

3. Apply custom sanitization rules

$data = [
    'name' => ' John Doe ',
    'email' => ' john@example.com ',
    'website' => ' https://example.com ',
    'bio' => " Hello\nI'm John "
];

$rules = [
    'name' => 'text',
    'email' => 'email',
    'website' => 'url',
    'bio' => 'textarea'
];

$cleaned = Sanitizer::byRules($data, $rules);
// returns [
//   'name' => 'John Doe',
//   'email' => 'john@example.com',
//   'website' => 'https://example.com',
//   'bio' => "Hello\nI'm John"
// ]

HTTP Client

The HttpClient class simplifies making HTTP requests in WordPress using wp_remote_* functions. It supports GET, POST, PUT, DELETE (and PATCH) and automatically decodes JSON responses.

Features

  • Perform requests with wp_remote_get, wp_remote_post, etc.
  • Supports safe URLs with reject_unsafe_urls
  • Automatically decodes JSON response bodies
  • Unified interface for REST APIs

Usage

1. Initialize the client

use MzeAhmed\WpToolKit\Http\HttpClient;

$client = new HttpClient();

2. Make a GET request

$response = $client->get('https://jsonplaceholder.typicode.com/posts');

if (is_wp_error($response)) {
    error_log($response->get_error_message());
} else {
    var_dump($response); // array of posts
}

3. Make a POST request

$response = $client->post('https://example.com/api/data', [
    'name' => 'John',
    'email' => 'john@example.com'
]);

4. Use safe mode (rejects unsafe URLs)

$response = $client->get('http://example.com', [], true); // safe mode enabled

📖 API Reference

MzeAhmed\WpToolKit\Http\HttpClient

Method Description Return Type
get() Perform an HTTP GET request `array
post() Perform an HTTP POST request `array
put() Perform an HTTP PUT request `array
delete() Perform an HTTP DELETE request `array
  • All methods accept:
    • $url (string) – The endpoint to query
    • $args (array) – Optional arguments (headers, timeout, etc.)
    • $safe (bool) – Enable WordPress URL validation with reject_unsafe_urls

Automatically decodes the JSON response body with json_decode(..., JSON_THROW_ON_ERROR).

mzeahmed/wp-toolkit 适用场景与选型建议

mzeahmed/wp-toolkit 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 716 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 01 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 mzeahmed/wp-toolkit 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-25