问题描述

我正在创建一个带有主题选项的简单框架。我已经在 functions.php 中划分了大量的代码,并将其放在特定的文件夹结构中。

现在在我的主要 functions.php 文件中,我只有 require_once 调用这些文件。

但是为了争论的缘故 – 我们来说最终会包含 20 个文件。

问题:

  1. 这是否可以以可见的方式影响 WP 性能?

  2. 最好把它全部保存在 1 个文件 (functions.php)

  3. 什么是最好的方法呢?

谢谢。

最佳解决方案

1. Does this have effect on WP performance in a visible way ?

如果它会对一些小文件产生真正的影响,那么它会产生影响比 WP:PHP 和服务器性能低的影响。真的有影响吗?不是真的。但您仍然可以自己开始进行性能测试。

2. Is it better to keep it all within 1 file (functions.php)

现在的问题是 「什么更好」?从整体文件加载时间?从文件组织的角度来看?无论如何,它没有任何区别。做一个这样的方式,所以你不会松动概述,并可以以一种愉快的方式维持结果。

3. what is the best way to go about this?

我通常做的只是挂在某个地方 (plugins_loadedafter_setup_theme 等 – 取决于你需要什么),然后只需要它们:

foreach ( glob( plugin_dir_path( __FILE__ ) ) as $file )
    require_once $file;

无论如何,你可以使它更复杂和灵活一些。看看这个例子:

<?php

namespace WCM;

defined( 'ABSPATH' ) OR exit;

class FilesLoader implements IteratorAggregate
{
    private $path = '';

    private $files = array();

    public function __construct( $path )
    {
        $this->setPath( $path );
        $this->setFiles();
    }

    public function setPath( $path )
    {
        if ( empty( $this->path ) )
            $this->path = plugin_dir_path( __FILE__ ).$path;
    }

    public function setFiles()
    {
        return $this->files = glob( "{$this->getPath()}/*.php" );
    }

    public function getPath()
    {
        return $this->path;
    }

    public function getFiles()
    {
        return $this->files;
    }

    public function getIterator()
    {
        $iterator = new ArrayIterator( $this->getFiles() );
        return $iterator;
    }

    public function loadFile( $file )
    {
        include_once $file;
    }
}

这是一个基本相同的类 (需要 PHP 5.3+) 。好处是它有点更细,所以您可以轻松地从需要执行特定任务的文件夹加载文件:

$fileLoader = new WCMFilesLoader( 'assets/php' );

foreach ( $fileLoader as $file )
    $fileLoader->loadFile( $file );

Update

当我们生活在一个新的 PHP v5.2 世界后,我们可以利用 FilterIterator 。最短变体示例:

$files = new FilesystemIterator( __DIR__.'/src', FilesystemIterator::SKIP_DOTS );
foreach ( $files as $file )
{
    /** @noinspection PhpIncludeInspection */
    ! $files->isDir() and include $files->getRealPath();
}

如果您必须坚持使用 PHP v5.2,那么您仍然可以使用 DirectoryIterator 和几乎相同的代码。

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。