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

问题描述 投票:0回答:3

我正在使用 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
php laravel laravel-4
3个回答
16
投票

您可以在应用程序目录中的某个位置创建一个新目录,例如,

app/libraries

然后在您的composer.json文件中,您可以在自动加载类映射中包含

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();

希望这有帮助!


6
投票

我认为你是对的兄弟,但是,我找到了另一种方法,也许不是正确的方法,但它有效。

就像这样,我创建了一个名为 Includes 的新文件夹并将我的文件放入其中,然后在 /app/start/global.php 中添加了这一行:

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

现在正在工作:D


0
投票

感谢您为 Stack Overflow 提供答案!

请务必回答问题。提供详细信息并分享您的研究! 但要避免……

寻求帮助、澄清或回应其他答案。 根据意见作出陈述;用参考资料或个人经验来支持它们。 要了解更多信息,请参阅我们关于撰写精彩答案的提示。

© www.soinside.com 2019 - 2024. All rights reserved.