在 PHP 中包含文件的最佳方式?
我目前正在开发一个 PHP Web 应用程序,我想知道以代码仍然可维护的方式包含文件 (include_once) 的最佳方式是什么。通过可维护,我的意思是,如果我想移动文件,很容易重构我的应用程序以使其正常工作。
我有很多文件,因为我尝试拥有良好的 OOP 实践(一个类 = 一个文件)。
这是我的应用程序的典型类结构:
namespace Controls
{
use Drawing\Color;
include_once '/../Control.php';
class GridView extends Control
{
public $evenRowColor;
public $oddRowColor;
public function __construct()
{
}
public function draw()
{
}
protected function generateStyle()
{
}
private function drawColumns()
{
}
}
}
I'm currently developping a PHP web application and I would like to know what is the best manner to include files (include_once) in a way where the code it is still maintanable. By maintanable I mean that if I want to move a file, It'd be easy to refactor my application to make it work properly.
I have a lot of files since I try to have good OOP practices (one class = one file).
Here's a typical class structure for my application:
namespace Controls
{
use Drawing\Color;
include_once '/../Control.php';
class GridView extends Control
{
public $evenRowColor;
public $oddRowColor;
public function __construct()
{
}
public function draw()
{
}
protected function generateStyle()
{
}
private function drawColumns()
{
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我曾经用以下内容开始我的所有 php 文件:
然后在该文件中,我将 require_once 所有其他需要的文件,例如,functions.php 或 globals.php,我将在其中声明所有全局变量或常量。这样您只需在一处编辑所有设置。
I used to start all my php file with:
Then in that file I would require_once all the other files that needed to be required, like functions.php for example, or globals.php where I would declare all global variables, or constants. That way you only have to edit all your setting at one place.
这取决于您想要完成的具体任务。
如果您想在文件和它们所在的目录之间有一个可配置的映射,您需要制定一个路径抽象并实现一些加载器函数来使用它。我就举个例子吧。
假设我们将使用像
Core.Controls.Control
这样的符号来引用(物理)文件Control.php
,该文件将在(逻辑)目录中找到核心.控件
。我们需要执行两部分的实现:Core.Controls
映射到物理目录/controls
。Control.php
。所以这是一个开始:
您将像这样使用加载器:
当然,这个示例是做一些有用的事情的最低限度,但您可以看到它允许您做什么。
如果我犯了任何小错误,我很抱歉,我是边写边写的。 :)
It depends on what you are trying to accomplish exactly.
If you want to have a configurable mapping between files and the directories in which they reside you need to work out a path abstraction and implement some loader functions to work with that. I 'll do an example.
Let's say we will use a notation like
Core.Controls.Control
to refer to the (physical) fileControl.php
which will be found in the (logical) directoryCore.Controls
. We 'll need to do a two-part implementation:Core.Controls
is mapped to the physical directory/controls
.Control.php
in that directory.So here's a start:
You would use the loader like this:
Of course this example is the bare minimum that does something useful, but you can see what it allows you to do.
Apologies if I have made any small mistakes, I 'm typing this as I go. :)