【问题标题】:How to include legacy PHP code hierarchy in Laravel如何在 Laravel 中包含遗留的 PHP 代码层次结构
【发布时间】:2015-04-11 01:51:08
【问题描述】:

我正在将一个遗留的 PHP 应用程序移植到 Laravel,并且需要将各种 PHP 文件中定义的函数包含到 Laravel 控制器中。将这些文件复制到 Laravel 项目中并不方便,因为它们仍将用于站点的非 Laravel 部分,并且我想确保代码仍然是共享的。如何在 Laravel 的某个地方使用 require() 以及所有旧 PHP 文件的相对路径?

例如在页面顶部我正在转换为 Laravel:

<?php

require("../include.php");
require_once("../../trades/trades_include.php");
require_once("account_access_page.php");
require_once("../includes/accounts.php");

如您所见,../include.php 包含其他具有相对路径的文件:

<?php

require_once("general.php");

require_once("../../config.php");
require_once("../../includes/utility.php");
require_once("../../includes/session_helper.php");

require_once("../../includes/date.php");
require_once("../../includes/form.php");
require_once("../../includes/mysql.php");
require_once("../../includes/page.php");
require_once("../../includes/table.php");

编辑:在composer.json 中包含文件并不能解决我的问题,因为嵌套的require_once()s 失败。有人知道解决方法吗?

【问题讨论】:

    标签: php laravel include require relative-path


    【解决方案1】:

    加载文件的最佳方式可能是使用 Composer。转到 Laravel 应用程序根目录中的 composer.json 并将其添加到 "autoload" 部分:

    "files": [
        "../include.php",
        "../../trades/trades_include.php"
        // and so on...
    ],
    

    路径相对于composer.json所在的目录。

    添加文件后,运行composer dump-autoload

    【讨论】:

    • @Andy 完成上述操作后,您可能需要在项目根目录中运行composer dump-autoload
    • @lukasgeiter 这是否意味着它们会为应用程序中的每条路由加载?最好只为需要它们的路线加载它们。
    • @lukasgeiter 我刚刚将文件添加到composer.json,但嵌套的require()s 不起作用。当我转到该页面时,我得到Warning: require_once(../../config.php): failed to open stream: No such file or directory in /vagrant/pub/ca/include.php on line 5
    • @Andy 是的,这将包含在每条路线中。嵌套的需求可能不起作用,因为现在相对路径是错误的......如果我找到有用的东西,我会回复你。
    • Argh,即使我复制了旧代码并将文件添加到 composer.json,这也不能正常工作,所包含文件中的全局变量似乎对其他人不可见文件。我还是 PHP 新手,我不太确定应该如何解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    相关资源
    最近更新 更多