arraypress/slurp

Slurp 库为在 WordPress 或通用 PHP 项目中动态包含 PHP 文件提供了一个强大且高效的解决方案。它支持递归包含文件,通过回调进行条件包含,并通过跟踪和记录包含的文件提供强大的调试功能。非常适合在插件或应用程序开发中进行有组织和高效的文件管理。

dev-main 2024-05-20 15:08 UTC

This package is auto-updated.

Last update: 2024-09-20 15:51:21 UTC


README

Slurp 库为在 WordPress 或通用 PHP 项目中动态包含 PHP 文件提供了一个强大且高效的解决方案。它支持递归包含文件,通过回调进行条件包含,并通过跟踪和记录包含的文件提供强大的调试功能。非常适合在插件或应用程序开发中进行有组织和高效的文件管理。

特性

  • 动态文件包含:自动包含指定目录中的 PHP 文件,简化项目设置和维护。
  • 递归包含:能够递归地包含子目录中的文件,确保不遗漏任何文件。
  • 条件包含:利用回调根据自定义逻辑(如用户角色或环境设置)条件性地包含文件。
  • 全局回调:为文件包含设置全局回调,将单一条件应用于所有包含的文件。
  • 排除能力:指定要排除的文件,以便精确控制加载的文件。
  • 调试支持:将所有包含的文件列表输出到文件中,有助于调试并确保文件管理的透明度。
  • 灵活使用:专为 WordPress 和通用 PHP 项目设计,在不同开发环境中提供灵活性。
  • 辅助函数:提供 slurp 辅助函数,简化在 WordPress 中的使用,便于将其集成到插件或主题中。

最低要求

  • PHP 7.4

安装

Slurp 是一个开发者库,而不是插件,这意味着您需要在您的项目中某处包含它。

您可以使用 Composer

composer require arraypress/slurp

基本文件包含

// Require the Composer autoloader.
require_once __DIR__ . '/vendor/autoload.php';

// Use the Slurp class from the ArrayPress\Utils namespace.
Use ArrayPress\Utils\Slurp;

// Create a Slurp instance for a specific directory. This prepares the Slurp class to handle file inclusions from the given directory.
$slurp = new Slurp(__DIR__);

// Include all PHP files from the specified subdirectory. The include method facilitates the inclusion of files from a directory relative to the base directory specified during instantiation.
$slurp->include( 'subdirectory' );

// Include all PHP files directly from the base directory. By calling the include method without any arguments, Slurp will include files from the base directory specified during its instantiation.
$slurp->include();

递归文件包含

// Include files from a directory and all its subdirectories.
$slurp->include( 'subdirectory', true );

多目录包含

$slurp->include( [ 'subdirectory1', 'subdirectory2' ] );

使用回调的条件文件包含

$slurp->include( [
    'subdirectory' => function( $filePath ) {
        // Only include files that contain 'module' in their name.
        return strpos( $filePath, 'module' ) !== false;
    }
] );

使用全局回调的条件文件包含

// Instantiate the Slurp class, setting the base directory and providing a global callback.
// The global callback uses is_admin() to determine if the file should be included,
// which is useful for admin-only features.
$slurp = new Slurp( __DIR__, function( $filePath ) {
    return is_admin(); // Global callback to include files only in the WordPress admin area.
} );

// Include PHP files from a specific directory. Thanks to the global callback,
// files will only be included if is_admin() returns true.
$slurp->include( [ 'admin', 'reports' ] );

初始化时排除特定文件

在创建 Slurp 类的新实例时,您可以通过将文件名数组作为构造函数的第三个参数传递,立即指定要排除的文件。当您事先知道哪些文件不应包含时,此方法非常有用。

// Initialize Slurp with an exclusion list.
$slurp = new Slurp( __DIR__, null, [ 'index.php', 'exclude.php' ] );
// Proceed to include all PHP files from the directory except 'index.php' and 'exclude.php'.
$slurp->include();

设置排除列表

使用 setExcluded 方法用新的文件名数组替换当前的排除文件列表。当您需要重新定义整个排除列表时,请使用此方法。

// Set a new list of specific files to be excluded from inclusion.
$slurp->setExcluded( ['newexclude.php', 'anotherexclude.php'] );
// This will override any previous exclusions and only exclude 'newexclude.php' and 'anotherexclude.php'.

添加到现有排除列表

使用 addExclusion 方法可以将一个或多个文件添加到现有的排除列表中。您可以传递单个文件名作为字符串或文件名数组。此方法在创建 Slurp 实例后动态调整排除列表时非常理想。

// Add a single file to the existing list of excluded files.
$slurp->addExclusion( 'additionalExclude.php' );

或者

// Add multiple files to the existing list of excluded files.
$slurp->addExclusion( ['additionalExclude1.php', 'additionalExclude2.php'] );

这些添加是累积的,不会覆盖现有的排除列表,而是扩展它。使用 addExclusion 方法确保所有指定的文件唯一添加,防止排除列表中的重复项。

覆盖全局回调

 // Global callback to include files only in the WordPress admin area.
$slurp->setCallback( function( $filePath ) {
    return is_admin();
} );

覆盖基本目录

// Include all other PHP files from the directory.
$slurp->setBaseDir( __DIR__ . '/includes' );

为调试输出加载的文件

// Dump the list of included files to a text file for debugging.
$slurp->dumpFiles( 'debug.txt' );

检索加载文件列表

$loadedFiles = $slurp->getFiles(); // Get an array of all the PHP files that have been included.
echo '<pre>';
print_r( $loadedFiles );
echo '</pre>';

从多个目录包含文件

// Assuming the Slurp class is already autoloaded via Composer
$slurp = new Slurp( __DIR__ );

// Include files from multiple directories.
$directories = [ 'directory1', 'directory2', 'directory3' ];
$slurp->include( $directories );

// You can also include files recursively from these directories
$slurp->include( $directories, true );

// Or include files based on a callback condition for each directory
$slurp->include( [
    'directory1' => function( $file ) { return strpos( $file, 'condition1' ) !== false; },
    'directory2' => function( $file ) { return strpos( $file, 'condition2' ) !== false; },
    'directory3' => null // Include all files from directory3
] );

使用白名单限制文件包含

白名单功能允许您指定一个目录列表,其中的文件可以安全地包含。当您只想从有限的位置包含文件时,这特别有用,可以进一步强化文件包含的安全性。

$slurp = new Slurp( __DIR__ );

// Add directories to the whitelist
$slurp->addToWhitelist( __DIR__ . '/safe_includes' );
$slurp->addToWhitelist( __DIR__ . '/more_safe_includes' );

// Including files from whitelisted directories
$slurp->include( 'safe_includes' ); // Allowed
$slurp->include( 'more_safe_includes' ); // Allowed

// Attempting to include files from a directory not in the whitelist will prevent inclusion
$slurp->include( 'unsafe_includes' ); // Prevented, no exception thrown but inclusion does not happen

在WordPress中使用辅助函数

示例 1:仅包含管理页面文件

本示例演示了如何仅在访问WordPress管理界面时包含指定目录中的文件。这对于加载特定于管理员的函数很有用。

add_action( 'admin_init', function() {
    $slurp = slurp(
        'admin', // Subdirectory containing admin files
        __DIR__, // Base directory targeted towards admin-related files
        false, // Non-recursive inclusion
        function ( $filePath ) {
            return is_admin();
        }
    );
    // Assume further setup or actions are taken with $slurp if needed
} );
示例 2:递归包含插件核心文件

本示例展示了如何递归地包含插件“includes”目录下的所有PHP文件,以确保子目录中的文件也被加载。

$slurp = slurp(
    'dev-tools', // Subdirectory containing development tools
    __DIR__, // Plugin root directory
    true, // Recursive inclusion to get all tools
    function ( $filePath ) {
        return defined('WP_DEBUG') && WP_DEBUG; // Only include if WP_DEBUG is true
    }
);
示例 3:基于站点上下文的条件包含

本示例使用全局回调函数,根据站点是否处于开发环境来条件性地包含文件。这对于加载调试工具或不应在生产环境中存在的额外资源非常有用。

$slurp = slurp(
    'dev-tools', // Subdirectory containing development tools
    __DIR__, // Plugin root directory
    true, // Recursive inclusion to get all tools
    function ( $filePath ) {
        return defined('WP_DEBUG') && WP_DEBUG; // Only include if WP_DEBUG is true
    }
);
// Development tools are loaded if the site is in debug mode
示例 4:排除特定文件的包含

在某些情况下,您可能想排除特定文件不被包含,例如示例文件或文档。本示例演示了如何使用excludedFiles参数来完成此目的。

$slurp = slurp(
    'includes', // Subdirectory containing plugin include files
    __DIR__, // Base directory for inclusion
    false, // Non-recursive inclusion
    null, // No global callback, include all files
    [ 'example.php', 'readme.md' ] // Exclude example and readme files from inclusion
);
// Only desired files are included, excluding the specified ones
示例 5:使用回调处理错误

本示例演示了如何使用errorCallback参数进行错误处理,这在记录错误或在WordPress环境中以特定方式处理错误时特别有用。

$slurp = slurp(
    'critical', // Include directly from the base directory
    __DIR__, // Base directory for critical functionalities
    false, // Non-recursive inclusion
    null, // No global callback, include all files
    [], // No files are excluded
    function ( $e ) {
        // Log error or handle it accordingly
        error_log( 'Error loading critical files: ' . $e->getMessage() );
    }
);
// Critical functionalities are attempted to be loaded, with error handling in place
示例 6:使用WordPress钩子的条件包含

本示例展示了如何使用slurp_hooked函数,仅在满足特定条件时(例如在WordPress管理区域)包含文件。这种设置对具有特定于管理员的功能的插件或主题非常有用。

// Attach the file inclusion process to the WordPress 'init' hook
slurp_hooked(
    'init',                                  // The WordPress hook to attach to
    __DIR__,                                 // Base directory for file inclusion
    'admin',                                 // Subdirectory containing admin files
    false,                                   // Non-recursive inclusion
    function ( $filePath ) {                 // Global callback to include files conditionally
        return is_admin();                   // Only include files if in the admin area
    },
    [ 'ignore-this.php', 'old-config.php' ], // Exclude specific files from inclusion
    10,                                      // Default priority
    1                                        // Number of arguments accepted by the function
);
// Files in the 'admin' subdirectory are included only when the user is in the admin area,
// and specified files are excluded from inclusion.

贡献

对本库的贡献非常受欢迎。在GitHub上提出问题或提交错误修复或新特性的pull请求。分享改进的反馈和建议。

许可证:GPLv2或更高版本

本程序是自由软件;您可以在自由软件基金会发布的GNU通用公共许可证的条款下重新分发和/或修改它;许可证的第2版,或者(根据您的选择)任何更高版本。

本程序的分发是希望它会有所用途,但没有任何保证;甚至没有关于适销性或特定用途的隐含保证。有关详细信息,请参阅GNU通用公共许可证。