Laravel 4.2:将PHP文件(库)包含到控制器中

scyqe7ek  于 2023-09-29  发布在  PHP
关注(0)|答案(2)|浏览(139)

我正在做一个使用Laravel 4.2的项目,我需要在控制器中包含一个PHP文件(一个将PDF转换为文本的库),然后返回一个带有文本的变量,有什么想法吗?
这是我的控制器

public function transform() {
    include ('includes/vendor/autoload.php');
}

而我的**/app/start/global.php**文件:

ClassLoader::addDirectories(array(
    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/includes',

));

下面是错误

include(includes/vendor/autoload.php): failed to open stream: No such file or directory
ugmeyewa

ugmeyewa1#

您可以在应用程序目录的某处创建新目录,例如app/libraries
然后在composer.json文件中,你可以在你的自动加载classmap中包含app/libraries

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "laravel/framework": "4.2.*",
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/libraries", <------------------ YOUR CUSTOM DIRECTORY
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "stable",
}

请确保在修改composer.json之后运行composer dump-autoload
让我们假设您的类名为CustomClass.php,并且它位于app/libraries目录中(因此完整路径为app/libraries/CustomClass.php)。如果您已经正确地对类进行了命名,那么按照约定,您的命名空间可能会命名为libraries。为了清楚起见,我们将命名空间称为custom,以避免与目录混淆。

$class = new \custom\CustomClass();

或者,您可以在app/config/app.php文件中给予别名:

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => array(
    ...
    'CustomClass'   => 'custom\CustomClass',
    ...
)

你可以从你的应用程序中的任何地方示例化这个类,就像你对任何其他类所做的那样:

$class = new CustomClass();

希望这对你有帮助!

2admgd59

2admgd592#

我想你是对的兄弟,但是,我找到了另一种方法,也许不是正确的方法,但它的工作。
是这样的,我创建了一个新的文件夹名为Includes,并把我的文件放在那里,然后在/app/start/global. php我添加了这一行:

require app_path().'/includes/vendor/autoload.php';

现在正在工作:D

相关问题