简体   繁体   English

如何加快我的 PHP 包括?

[英]How can I speed up my PHP includes?

I have once PHP file that I include to pretty much everything I call.我曾经有一次 PHP 文件,我将其包含在我调用的几乎所有内容中。 This one include file has several other php files that it includes.这个包含文件包含其他几个 php 文件。 The reason I use this one file for all my including is because I have path differences between my dev and production server and it is nice to only have to include one file and know that I have the classes that I need right there.我将这个文件用于所有包含的原因是因为我的开发服务器和生产服务器之间存在路径差异,并且只需要包含一个文件并且知道我有我需要的类就很好。

Is there any easy way to cache the file, or something to speed up my load times?有什么简单的方法可以缓存文件,或者有什么方法可以加快我的加载时间吗?

You can install an opcode cache for PHP您可以为 PHP 安装操作码缓存

An opcode cache optimizes performance by removing the compilation time of PHP scripts by caching the compiled state of PHP scripts into RAM and uses the compiled version straight from the RAM.操作码缓存通过将 PHP 脚本的已编译 state 缓存到 RAM 中来消除 PHP 脚本的编译时间来优化性能,并直接使用 RAM 中的编译版本。 This will increase the rate of page generation time.这将增加页面生成时间的速率。 It also means your files will only be included once.这也意味着您的文件只会被包含一次。

There are many ways to handle path differences than do not involve loading everything every time.有很多方法可以处理路径差异,而不是每次都加载所有内容。 You can, for instance, define a constant and use it as prefix in all your file system operations:例如,您可以定义一个常量并将其用作所有文件系统操作的前缀:

define('DOC_ROOT', '/var/www/foo');
require_once DOC_ROOT . '/lib/bar.php';

Or you can rely in your system's DOCUMENT_ROOT variable (if set and correct):或者您可以依赖系统的 DOCUMENT_ROOT 变量(如果设置且正确):

require_once $_SERVER['DOCUMENT_ROOT'] . '/lib/bar.php';

Or you can use class autoloading .或者您可以使用class 自动加载 Or you can use include_path .或者您可以使用include_path

Apart from that, PHP will always find and parse every file with PHP source code you instruct it to, every time you run your script.除此之外,每次运行脚本时,PHP 将始终使用您指示的 PHP 源代码查找解析每个文件。 You can shorten the second part if you install an opcode cache .如果您安装操作码缓存,您可以缩短第二部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM