Laravel - 如何访问自定义类中的 App 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27843441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:39:19  来源:igfitidea点击:

Laravel - how do you access App object in a custom class?

phplaravel

提问by razvansg

I have a custom class in app/libraries/data/Data.php where i want to return a connection to a database.

我在 app/libraries/data/Data.php 中有一个自定义类,我想在其中返回到数据库的连接。

The problem is i need to dynamically load a database that doesn't(and can't) exist in the config file.

问题是我需要动态加载一个在配置文件中不存在(也不可能)的数据库。

I found a nice solution, and to be honest it was exactly what i was hoping for, but it seems i cant access the App object from there.

我找到了一个不错的解决方案,老实说这正是我所希望的,但似乎我无法从那里访问 App 对象。

<?php
namespace libraries\data;
use DB;

class Data 
{

    public function db($name, $firma = false)
    {

        if ($name == 'firma') {

            $config = App::make('config');
            $connections = $config->get('database.connections');

            $newConnection = $connections[$config->get('database.firma_%s')];

            $name = sprintf('firma_%s', $firma);
            $newConnection['database'] = $name;

            App::make('config')->set('database.connections.'.$name, $newConnection);
        }

        return DB::connection($name);
    }
}
?>

Update: of course i tried "use App;" (d`oh) and of course it didn't work. And of course it works now.

更新:当然我试过“使用应用程序”;(d`oh)当然它没有用。当然,它现在有效。

回答by Robert Bakker

You could also use the app()helper function which returns the application instance. And $config = app('config');to get the config object.

您还可以使用app()返回应用程序实例的辅助函数。并$config = app('config');获取配置对象。

回答by Sascha Galley

Your are in the namespace libraries\data. Either you add use App;or you call the App methods with \App::.

你在命名空间中libraries\data。您可以添加use App;或使用\App::.

回答by Needpoule

Since you define a custom namespace libraries\data, the application will try to find the App class in the libraries\data namespace.

由于您定义了自定义命名空间libraries\data,应用程序将尝试在 libraries\data 命名空间中查找 App 类。

If you want to use the laravel App class you need to write this:

如果你想使用 laravel App 类,你需要这样写:

 $config = \App::make('config');

Or add use App;at the top of your file like you did with the DB class.

或者use App;像在 DB 类中那样在文件顶部添加。