php - 拉维尔 4.2 : Include a PHP file (library) into controller

标签 php laravel laravel-4

我正在使用 Laravel 4.2 做一个项目,我需要将一个 PHP 文件(一个将 PDF 转换为文本的库)包含到 Controller 中,然后返回一个带有文本的变量,知道怎么做吗?

这是我的 Controller :

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

最佳答案

您可以在您的应用程序目录中的某个位置创建一个新目录,例如,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();

希望这对您有所帮助!

关于php - 拉维尔 4.2 : Include a PHP file (library) into controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25695408/

相关文章:

javascript - 以更低的成本找到最佳组合

php - 在 Laravel 中定位慢代码

PHP 和 SMTP 不能一起工作

laravel - 如何在 laravel 5 的所有 Controller 和 View 页面中使用 token 号?

php - 找不到简单查询的使用示例并且有问题

php - 如何在 Laravel Eloquent 中指定多个一对一关系?

laravel - 如何在 Laravel 4 中查询和过滤软删除的 Eloquent 模型

php - 我如何在 Laravel 中使用 BETWEEN 和 AND

php - 如何在 Bootstrap 范围 slider 中获得两个值?

php - 在 PHP 页面中打印 .out 文件的输出