简体   繁体   English

在php中,我们是否需要在所有文件中包含文件,还是有更好的方法?

[英]In php do we need to do include in all files or is there a better way?

I have a DB configuration (db.php) in the root folder 我在根文件夹中有一个数据库配置(db.php)

MySQL with PDO_MYSQL 带有PDO_MYSQL的MySQL

$host = "";
$user = "";
$pass = "";
$dbname = "";
# connect to the database
$DBH = new PDO("mysql:host=$host;port=3306;dbname=$dbname", $user, $pass,array(PDO::ATTR_PERSISTENT => true));
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I figured that if I need a DB connection I would need to do 我发现如果需要数据库连接,我需要做

<?php
include '../../db.php';

In all the PHP files that need the DB connection. 在所有需要DB连接的PHP文件中。

My question is do I need to do "include" everytime I need a DB connection or is there a way to set this connections setting Global so I can just call $DBH->prepare(SQLSTATEMENT) any where in the project and it will work. 我的问题是我是否需要在每次需要数据库连接时都进行“包含”操作,或者是否可以通过全局方式设置此连接,所以我可以在项目中的任何位置调用$ DBH-> prepare(SQLSTATEMENT),它将起作用。

Or is there a better way to handle DB connection settings? 还是有更好的方法来处理数据库连接设置?

The short answer: Yes , you need to include your DB file in every page that uses it. 简短的回答: 是的 ,您需要在使用DB文件的每个页面中包括它。

The long answer... PHP doesn't load every PHP file in existence every time a script is run, so it has to know where your variables/classes are coming from. 长话大说... PHP不会在每次运行脚本时加载存在的每个PHP文件,因此它必须知道您的变量/类来自何处。 However, there are a couple of ways to not have to include the db file each time. 但是,有两种方法不必每次都包含db文件。 Your options for this are that you can auto-prepend the file, you can have your file included from another file that already has the db variable set up, or you can set your code up in an OO manner and include an autoload file. 为此,您可以选择自动添加文件,可以将文件包含在已设置db变量的另一个文件中,也可以以OO方式设置代码并包含自动加载文件。

auto-prepend 自动添加

If every file you have on this server needs to access the database AND you have access to the php.ini file, you can set the auto-prepend-file option in your php.ini. 如果此服务器上的每个文件都需要访问数据库,并且可以访问php.ini文件,则可以在php.ini中设置auto-prepend-file选项。 This will automatically include the file in every file as if loaded by require . 这将自动在每个文件中包括该文件,就像由require加载一样。 If you go this route, make sure you are checking in your db file if it's already been loaded: 如果您采用这种方式,请确保您正在检查数据库文件是否已加载:

your-db-file.php your-db-file.php

if (!defined('MYPROJECT_DB_FILE_LOADED')) {
    define('MYPROJECT_DB_FILE_LOADED', true);
    // load DBH and stuff here.
}

include from another file 从另一个文件包含

Another good option that doesn't require you messing with the php.ini file is to structure your code in a way that your php files are loaded from a parent file. 另一个不需要您弄乱php.ini文件的好选择是,以从父文件加载php文件的方式来构造代码。 A great example of this is how WordPress handles loading its pages. 一个很好的例子是WordPress如何处理其页面加载。 WordPress has a main index.php file that checks the URL and loads pages based on the path. WordPress有一个主要的index.php文件,该文件检查URL并根据路径加载页面。 Pages included from this file have access to the variables from that file. 该文件中包含的页面可以访问该文件中的变量。 A simple example of how to set that up could be like this: 一个简单的例子是这样的:

.htaccess in root directory (assuming mod_rewrite is enabled) 根目录中的.htaccess(假设启用了mod_rewrite)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.* /index.php

This will route everything through your index.php file which could have something like this: 这将通过您的index.php文件路由所有内容,其中可能包含以下内容:

// Do all of your DBH stuff
$DBH = ...

$url = trim($_SERVER['REQUEST_URI'], '/');
if ($url === 'some/path/here') {
    include 'other-file.php';
}

Then, other-file.php would have access to the DBH variable: 然后, other-file.php将有权访问DBH变量:

$DBH->do_something();

use OO (object orientated) design and include autoload 使用OO(面向对象)设计并包括自动加载

The most common method (and imho the best) is to structure your code in an OO way and just include the autoload file. 最常见的方法(最好的方法是恕我直言,最好的方法)是以OO方式构造代码,并仅包含自动加载文件。 A great example of this is how composer installs dependencies into your project and generates a vendor/autoload.php file to be included. 一个很好的例子是composer如何将依赖项安装到项目中并生成一个vendor / autoload.php文件。

One simple approach to this would be to namespace your classes, place them all in a directory, and then create an autoload file (using spl_autoload_register ). 一种简单的方法是为类命名空间,将所有类放置在目录中,然后创建一个自动加载文件(使用spl_autoload_register )。 Here is a quick (and untested) example of how you could accomplish that: 这是一个如何完成此任务的快速示例(未经测试):

Inside /projectroot/lib for example: 在/ projectroot / lib内部,例如:

/projectroot/lib/MyDB.php /projectroot/lib/MyDB.php

namespace MyProject;

if (!class_exists('\MyProject\MyDB')) {
    class MyDB {
        // Add some DB methods in here.
    }
}

/projectroot/lib/autoload.php /projectroot/lib/autoload.php

if (!defined('MYPROJECT_SPL_AUTOLOAD_REGISTERED')) {
    define('MYPROJECT_SPL_AUTOLOAD_REGISTERED', true);
    spl_autoload_register(function($class) {
        $class = explode($class, '\\');
        if (array_shift($class) === 'MyProject') {
            require __DIR__.'/'.join('/', $class);
        }
    });
}

Then, from any other file you have: 然后,从任何其他文件中获得:

require '/projectroot/lib/autoload.php';

$db = new \MyProject\MyDB();

I realize that the last option doesn't stop you from having to use an include in every file, but you always include the same file (so you can copy/paste), AND any class namespaced correctly in your lib folder will automatically be included any time you need it, so it will work with more than just your db stuff. 我意识到最后一个选项不会阻止您在每个文件中使用包含,但是您始终包含相同的文件(以便可以复制/粘贴),并且将自动在lib文件夹中正确命名的任何类都将被包含在内。任何时候您都需要它,因此它不仅可以与数据库一起工作。

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

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