作曲家要求和使用非类文件 [英] composer require and use non-class file

查看:52
本文介绍了作曲家要求和使用非类文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Composer的新手,我只是想不知道如何自动加载非基于类的文件。

I'm new to Composer and I just can't figure out on how to autoload non-class based files.

我尝试将文件添加到composer.json中的 files 数组中,然后运行 composer install 但我没有运气。

I have tried adding the file to the files array in composer.json and then running composer install but I had no luck.

我的composer.json看起来像:

My composer.json looks like:

{
  "name": "app",
  "description": "",
  "require": {
    "mongodb/mongodb": "^1.2"
  },
    "autoload":{
        "files":["src/lib/config.php"]
    }
}

这是基于非类的文件config.php

Here is the non-class based file, config.php

$foo = "Hello";

这就是我所说的:

require_once("vendor/autoload.php");

echo $foo;

以上抛出错误未定义变量:foo

或者文件可能被自动加载,或者我使用的是错误的命名空间。如果是这种情况,我将如何调用该文件。

Or perhaps the file might be autoloaded and maybe I could be in the wrong namespace. If this is the case, how would I call this file.

推荐答案

我不同意@MarkBaker的评论。实际上,文件将自动加载,但是无法在此类文件中声明变量。

I disagree with @MarkBaker comment. In fact file will be automatically loaded but it's impossible to declare variables in such files.

例如,如果您放入此 config.php 提供以下功能:

For example if you put into this config.php file the following function:

function hello()
{
   echo "hello world";
}

,而不显示 $ foo ,您将像这样调用此方法:

and instead of displaying $foo you will call this method like so:

hello();

您将得到预期的结果。

变量不可见的原因是通过Composer加载文件的方式:

The reason why variable is not visible is the way file is loaded via Composer:

function composerRequire4b299eb5732a472abef81c6ea06043af($fileIdentifier, $file)
{
    if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
        require $file;

        $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
    }
}

如您所见,方法内部需要文件,因此已全部定义变量仅在此方法中具有作用域,因此在此之后它们将不可见(这就是PHP的工作方式)。

As you see file is required inside method so all defined variables have scope only in this method so they won't be visible after that (this is how PHP works).

所以回答我们的问题是预期的行为。您不应该在Composer的自动加载文件中声明任何变量。如果您需要类似的功能,则应该手动要求文件。

So answering our question this is expected behavior. You shouldn't declare any variables in auto-loaded files by Composer. If you need similar functionality, you should require file manually.

当然,我认为您不应该在配置文件中声明变量。您应该返回设置数组,然后将此数组分配给全局 $ config 变量(最简单的解决方案),或者使用将保留这些设置并从此类中获取配置的类(某些方法例如是用Laravel制造的。)

Of course I don't think you should really declare variables in configuration files. You should rather return array of settings and then assign this array to global $config variable (simplest solution) or use class that will hold those settings and get configuration from this class (something like this is made in Laravel for example).

这篇关于作曲家要求和使用非类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆