laravel Lumen - 在运行时创建数据库连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37215265/
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 13:48:03  来源:igfitidea点击:

Lumen - Create database connection at runtime

phppostgresqlsqlitelaravellumen

提问by BernalCarlos

In a Lumen project, I need to create database connections on runtime, but I keep getting a "Database [...] not configured" error, each time I try to use a recently created connection.

在 Lumen 项目中,我需要在运行时创建数据库连接,但每次尝试使用最近创建的连接时,我都会收到“数据库 [...] 未配置”错误。

This is my test code on routes.php:

这是我在 routes.php 上的测试代码:

<?php

$app->get('/', function () use ($app) {

    $config = $app->make('config');
    $config->set('database.connections.retail_db', [
        'driver'   => 'pgsql',
        'host'     => env('RETAIL_DB_HOST', 'localhost'),
        'port'     => env('RETAIL_DB_PORT', 5432),
        'database' => env('RETAIL_DB_DATABASE', 'forge'),
        'username' => env('RETAIL_DB_USERNAME', 'forge'),
        'password' => env('RETAIL_DB_PASSWORD', ''),
        'charset'  => env('RETAIL_DB_CHARSET', 'utf8'),
        'prefix'   => env('RETAIL_DB_PREFIX', ''),
        'schema'   => env('RETAIL_DB_SCHEMA', 'public'),
    ]);
    return app('db')->connection('retail_db')->select("SELECT * FROM users");

});

This code is supposed to work on Laravel, but I can't find any information regarding Lumen.

此代码应该适用于 Laravel,但我找不到有关 Lumen 的任何信息。

I'm using the latest Lumen version.

我正在使用最新的 Lumen 版本。

回答by codedge

There is one main problem with the method you are going for:

您要使用的方法存在一个主要问题:

You did not initialize any configuration object. Lumen by default has no traditional config object set, until you create a configdirectory in your root folder.

您没有初始化任何配置对象。Lumen 默认没有传统的配置对象集,直到你config在你的根文件夹中创建一个目录。

As written in the Lumen configuration docs:

正如Lumen 配置文档中所写:

All of the configuration options for the Lumen framework are stored in the .env file.

Lumen 框架的所有配置选项都存储在 .env 文件中。

The approach you are going for requires the traditional config object as used in Laravel.

您要采用的方法需要 Laravel 中使用的传统配置对象。

To get that object and your new retail_dbdatabase connection working:

要使该对象和您的新retail_db数据库连接正常工作:

  • Create a configfolder in your project root
  • Copy the file vendor/laravel/lumen-framework/config/database.phpto this config folder
  • Initialize the database configuration object in your bootstrap/app.phpwith $app->configure('database');(put it at line 28)
  • config在您的项目根目录中创建一个文件夹
  • 将文件复制vendor/laravel/lumen-framework/config/database.php到此配置文件夹
  • 在你的bootstrap/app.phpwith 中初始化数据库配置对象$app->configure('database');(放在第 28 行)

Your folder structure looks like this now:

您的文件夹结构现在如下所示:

├── app
├── bootstrap
├── config
   └── database.php
├── database
├── public
├── resources
├── storage
├── tests
└── vendor

Of course you can remove those connections you don't need from the connections array in app/config/database.phpby commenting or removing them completely.

当然,您可以app/config/database.php通过注释或完全删除它们来从连接数组中删除那些不需要的连接。

app/config/database.php

应用程序/配置/数据库.php

'connections' => [

        /*'testing' => [
            'driver' => 'sqlite',
            'database' => ':memory:',
        ],*/

        'sqlite' => [
            'driver'   => 'sqlite',
            'database' => env('DB_DATABASE', base_path('database/database.sqlite')),
            'prefix'   => env('DB_PREFIX', ''),
        ],

        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'port'      => env('DB_PORT', 3306),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => env('DB_CHARSET', 'utf8'),
            'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
            'prefix'    => env('DB_PREFIX', ''),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],
]

Your bootstrap/app.phpwith the changes:

你的bootstrap/app.php有变化:

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

//$app->withFacades();
// $app->withEloquent();

$app->configure('database');

Now you can use the code you already have in your routes.php.

现在您可以使用您的routes.php.

To delete your retail_dbconnection, just set it to null:

要删除您的retail_db连接,只需将其设置为null

$config->set('database.connections.retail_db', null);