問題描述
我正在創建一個帶有主題選項的簡單框架。我已經在 functions.php 中劃分了大量的代碼,並將其放在特定的文件夾結構中。
現在在我的主要 functions.php 文件中,我只有 require_once 調用這些文件。
但是為了爭論的緣故 – 我們來説最終會包含 20 個文件。
問題:
-
這是否可以以可見的方式影響 WP 性能?
-
最好把它全部保存在 1 個文件 (functions.php)
-
什麼是最好的方法呢?
謝謝。
最佳解決方案
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_loaded,after_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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。