简体   繁体   English

Laravel为整个项目设置动态配置变量

[英]Laravel set dynamic config variable for whole project

I'm working on a CMS with Laravel to manage other databases. 我正在与Laravel合作开发CMS,以管理其他数据库。 Now i use the config function to create a temporary config variable. 现在,我使用config函数创建一个临时配置变量。 I do this for the external database and it also works. 我为外部数据库执行此操作,并且它也有效。

This is what my code looks like now: 这是我的代码现在的样子:

$website = Website::where('hash', '=', $hash)->first();

config(['database.connections.extern.host' => $website->db_host]);
config(['database.connections.extern.database' => $website->db_name]);
config(['database.connections.extern.username' => $website->db_username]);
config(['database.connections.extern.password' => $website->db_password]);

The problem is now, wherever I want to call the external database, I should do this. 现在的问题是,无论我想在哪里调用外部数据库,都应该这样做。 That is of course not convenient. 那当然不方便。

Does anyone know a solution to this 'problem'? 有谁知道解决这个“问题”的方法?

You can loop through Website model and set config file at the startup and use website's hash as the key: 您可以循环浏览网站模型并在启动时设置配置文件,并使用网站的哈希作为键:

foreach (Website::all() as $website) {
    config(['database.connections.'.$website->hash.'.host' => $website->db_host]);
    ...
}

And then use website hash to connect to relevant DB: 然后使用网站哈希连接到相关的数据库:

DB::connection($hash) ...

Anyway this is not a good way to manage other databases if they are on different hosts. 无论如何,如果其他数据库位于不同的主机上,这不是管理其他数据库的好方法。 You better use web services technique to do such work. 您最好使用Web服务技术来进行此类工作。 Connecting to external DB is potentially insecure. 连接到外部数据库可能不安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM