承接 hstanleycrow/easyphpdatatablecrud 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

hstanleycrow/easyphpdatatablecrud

Composer 安装命令:

composer require hstanleycrow/easyphpdatatablecrud

包简介

PHP UI builder that renders ready-to-use CRUD datatables on top of EasyPHPDatatables

README 文档

README

PHP UI builder that renders ready-to-use CRUD datatables on top of EasyPHPDatatables. You describe a table once (columns, joins, action buttons) and the builder outputs the markup, the CSS/JS resource tags and the DataTables server-side wiring.

Spanish version: README.es.md.

Scope: what it does and what it doesn't

This library owns the listing (the "read" of CRUD): it renders the table, wires the DataTables server-side processing and paints the action buttons. The buttons are just links to paths you choose (user/edit/1/, user/delete/1/, user/add/). Building the create / edit / delete pages behind those links is your responsibility — the library does not generate forms or perform writes.

Requirements

  • PHP ^8.2

  • ext-pdo, ext-json

  • A MySQL database with at least one table to list

  • hstanleycrow/easyphpdatatables ^2.0

  • PHP ^8.2

  • ext-pdo, ext-json

  • A PDO-MySQL database

  • hstanleycrow/easyphpdatatables ^2.0

Installation

composer require hstanleycrow/easyphpdatatablecrud

How it works

Three pieces cooperate:

  1. A definition class describing the table (columns, primary key, join, buttons). The library resolves it from DT_DEFINITIONS_NAMESPACE + the model name, so new DatatableUIBuilder('user') loads {DT_DEFINITIONS_NAMESPACE}\User.
  2. A page that renders the table and points it at an AJAX endpoint.
  3. An AJAX endpoint that answers DataTables server-side processing requests.

A full runnable sample lives in examples/.

Running the bundled example

The example lists a users table and shows styled action buttons built with EasyPHPWebComponents icons.

  1. Install dependencies (dev deps included, so the example buttons resolve):

    composer install
  2. Create a database and load the sample table + seed rows:

    mysql -u root -p your_database < examples/schema.sql

    The table columns must match what the definition references. See examples/schema.sql and examples/Definitions/User.php.

  3. Configure the environment. Copy the template and fill in your database:

    cp examples/.env.example examples/.env

    At minimum set DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD and keep DT_DEFINITIONS_NAMESPACE pointing at the example definitions.

  4. Serve it and open the page:

    php -S 127.0.0.1:8000 -t examples/public
    # http://127.0.0.1:8000/

    Under Apache (XAMPP) browse to the examples/public/ folder with the trailing slashsetAjaxUrl('datatables.php') is resolved relative to the current URL.

Quick start

The datatable only reads columns that actually exist. Every db_name (and any join in getJoinQuery()) must reference real columns, or the AJAX endpoint returns an SQL error.

1. Define the table

<?php

namespace App\Datatables;

class User
{
    public string $dbTable = 'users';
    public string $model = 'user';
    public string $primaryKey = 'id';

    public function getColumns(): array
    {
        return [
            ['view_name' => 'Id',   'db_name' => '`a`.`id`',   'field' => 'id',   'format' => 'text'],
            ['view_name' => 'Name', 'db_name' => '`a`.`name`', 'field' => 'name', 'format' => 'text'],
        ];
    }

    public function getButtons(): array
    {
        return [
            ['button_id' => 'edit', 'view_name' => 'Edit', 'db_name' => '`a`.`id`', 'field' => 'id', 'path' => 'edit', 'buttonText' => 'Edit'],
        ];
    }

    public function getJoinQuery(): string
    {
        return "FROM `users` AS `a`";
    }

    public function getExtraCondition(): string
    {
        return "";
    }
}

2. Render the page

<?php

require 'vendor/autoload.php';

use Dotenv\Dotenv;
use hstanleycrow\EasyPHPDatatableCRUD\DatatableUIBuilder;

Dotenv::createImmutable(__DIR__)->load();

$datatable = new DatatableUIBuilder(DTDefinition: 'user');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <?= $datatable->autoLoadCssResources() ?>
</head>
<body>
    <div class="container">
        <?= $datatable->setTableId('users')->render() ?>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <?= $datatable->autoLoadJsResources() ?>
    <?= $datatable->setAjaxUrl('datatables.php')->autoLoadDatatableJS() ?>
</body>
</html>

setAjaxUrl() is required before autoLoadDatatableJS(); otherwise it throws.

3. Expose the AJAX endpoint

datatables.php in your webroot:

<?php

require 'vendor/autoload.php';

use Dotenv\Dotenv;
use hstanleycrow\EasyPHPDatatables\SSP;

// EasyPHPDatatables does not load .env by itself: populate $_ENV first,
// or inject your own connection with SSP::handle($pdo).
Dotenv::createImmutable(__DIR__)->load();

SSP::handle();

Related tables (joins)

Real CRUDs rarely show a single table. The definition builds the SELECT from your columns and the FROM ... JOIN from getJoinQuery(), so you can pull columns from related tables. The conventions:

  • The main table is aliased a; each joined table gets its own alias (b, c, …).
  • getJoinQuery() returns only the FROM ... JOIN ... part. The library builds the SELECT for you from every column's db_name.
  • A column coming from a joined table uses that table's alias in db_name and must declare an as alias, so its value lands under its own key in the result row.
public function getColumns(): array
{
    return [
        ['view_name' => 'Id',     'db_name' => '`a`.`id`',   'field' => 'id',     'format' => 'text'],
        ['view_name' => 'Name',   'db_name' => '`a`.`name`', 'field' => 'name',   'format' => 'text'],
        // Column from the joined table: alias `b`, plus an `as` alias.
        ['view_name' => 'Status', 'db_name' => '`b`.`name`', 'field' => 'status_name', 'as' => 'status_name', 'format' => 'text'],
    ];
}

public function getJoinQuery(): string
{
    return "FROM `users` AS `a` INNER JOIN `user_status` AS `b` ON (`a`.`user_status_id` = `b`.`id`)";
}

Use getExtraCondition() for a fixed WHERE (e.g. "WHERE a.active = 'S'") that applies on top of the DataTables search. A complete, runnable version of this join lives in examples/Definitions/User.php, with its schema in examples/schema.sql.

Public API (DatatableUIBuilder)

Method Returns Description
__construct(string $DTDefinition, ?array $dtDisabledIdButtons = []) Loads the definition resolved from DT_DEFINITIONS_NAMESPACE.
setAjaxUrl(string $ajaxUrl) self URL of the server-processing endpoint. Required before autoLoadDatatableJS().
setTableId(string $tableId) self Sets the HTML table id.
addCssClass(string $class) self Appends a CSS class to the table.
setDTLanguage(string $language) self en, es or es-MX.
setDTRowsPerPage(int $rowsPerPage = 25) self Default page size.
setFramework(string $framework) void bootstrap3|bootstrap4|bootstrap5|bulma|foundation|jquery|semantic.
changeButtonsToRender(array $buttonsToRender = []) self Toggle the built-in add button, e.g. ['add' => false].
setAddButtonClass(string $class) self Swap the class used to render the add button.
render() string The datatable markup wrapped with the add-button container.
autoLoadCssResources() string <link> tags required by the datatable.
autoLoadJsResources() string <script> tags required by the datatable.
autoLoadDatatableJS() string Inline init script. Requires setAjaxUrl().

Styled action buttons

Without a buttonClass, buttons render as plain <a> links. To get styled buttons (Bootstrap classes, icons, …), point each button at a class that receives the target href and returns HTML from render():

// In the definition's getButtons():
[
    'button_id'   => 'edit',
    'view_name'   => 'Edit',
    'db_name'     => '`a`.`id`',
    'field'       => 'id',
    'path'        => 'edit',
    'buttonText'  => 'Edit',
    'buttonClass' => \App\Buttons\EditButton::class,
],

The built-in "add" button is swapped separately, on the builder:

$datatable->setAddButtonClass(\App\Buttons\AddButton::class);

See examples/Buttons/ for AddButton, EditButton and DeleteButton built on top of EasyPHPWebComponents icons, and examples/Definitions/User.php for how they are wired in. Load a CSS framework and an icon set (e.g. Bootstrap + Font Awesome) on the page for the classes to take effect.

Configuration

The datatable reads its configuration from $_ENV. Copy examples/.env.example and adjust:

Variable Purpose
DATABASE_HOST / DATABASE_NAME / DATABASE_USERNAME / DATABASE_PASSWORD Connection.
DATABASE_PORT Optional, defaults to 3306.
DATABASE_CHARSET Optional charset name, defaults to utf8mb4.
DT_DEFINITIONS_NAMESPACE Namespace where your definition classes live.
DT_LANGUAGE en, es or es-MX.
DT_PAGE_LENGTH, DT_DATE_FORMAT, DT_MONEY_SYMBOL, … Formatting and presentation.

Testing

composer install
vendor/bin/phpunit

License

MIT.

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-07-10

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固