访问示例以外的类方法实例的正确方法是什么?
我有如下代码:访问示例以外的类方法实例的正确方法是什么?
import std.stdio;
import database;
import router;
import config;
import vibe.d;
void main()
{
Config config = new Config();
auto settings = new HTTPServerSettings;
settings.port = 8081;
settings.bindAddresses = ["::1", "127.0.0.1"];
auto router = new URLRouter();
router.get("/*", serveStaticFiles("./html"));
Database database = new Database(config);
database.MySQLConnect(); // all DB methods are declared here
router.registerRestInterface(new MyRouter(database));
router.get("*", &myStuff); // all other request
listenHTTP(settings, router);
logInfo("Please open http://127.0.0.1:8081/ in your browser.");
runApplication();
}
void myStuff(HTTPServerRequest req, HTTPServerResponse res) // I need this to handle any accessed URLs
{
writeln(req.path); // getting URL that was request on server
// here I need access to DB methods to do processing and return some DB data
}
我需要创建router.get("*", &myStuff);
处理任何网址,不涉及任何REST实例。
,我不知道如何从myStuff()
我有vibe.d没有经验去DB方法访问,但是这可能是一个解决方案的问题:
Database database;
shared static this(){
Config config = new Config();
database = new Database(config);
}
void main(){
(...)
void myStuff(HTTPServerRequest req, HTTPServerResponse res){
database.whatever;
}
有不尝试过,但使用“部分”可能是一个解决方案。
https://dlang.org/phobos/std_functional.html#partial
void myStuff(Database db, HTTPServerRequest req, HTTPServerResponse res) { ... }
void main()
{
import std.functional : partial;
...
router.get("*", partial!(myStuff, database));
...
}
部分创建了绑定到一个给定值的第一个参数的函数 - 这样的调用者不需要了解它。我个人不喜欢全局变量/,单身/等,并尝试注入依赖项。虽然实现可能会变得更加复杂,但这确实简化了很多测试。
https://en.wikipedia.org/wiki/Dependency_injection#Constructor_injection
当注入依赖这样你也可以得到有关所需组件的快速概述调用这个函数:
上面的例子这里提到注入类似构造器注入方式的依赖。如果使用其他方法增加依赖关系的数量 - 例如。注入一个ServiceLocator。
https://martinfowler.com/articles/injection.html#UsingAServiceLocator
罗尼
作为一种替代的部分,你可以用closure实现partial application:
router.get("*", (req, resp) => myStuff(database, req, resp));
// ...
void myStuff(Database db, HTTPServerRequest req, HTTPServerResponse res)
// ...
myStuff
现在已经从周边范围注入database
。
正确,比部分更好! – duselbaer
使'数据库''共享'并将其移动到模块范围? –