HerikLyma / CPPWebFramework

​The C++ Web Framework (CWF) is a MVC web framework, Open Source, under MIT License, using C++ with Qt to be used in the development of web applications.
MIT License
445 stars 119 forks source link

Pass database between controllers #32

Closed marcs7 closed 3 years ago

marcs7 commented 3 years ago

This is a duplicate issue of #28 but i hope to find an answer. I'm looking for a way to pass the DB from a controller manager to a controller without extend the class. Thanks for any reply and i hope this issue will not close without an answer.

HerikLyma commented 3 years ago

Hello.

Please check the REST Web Service - Example:

include <cwf/sqlquery.h>

include <cwf/cppwebapplication.h>

include <cwf/sqldatabasestorage.h>

/*

CWF::SqlDatabaseStorage storage("QPSQL", "localhost", "postgres", "postgres", "1234", 5432);

class CountriesController : public CWF::Controller { public: void doGet(CWF::Request &request, CWF::Response &response) const override { CWF::SqlQuery qry(storage); qry.exec("select * from countries"); response.write(qry.toJson()); } };

//Call //http://localhost:8080/countries int main(int argc, char *argv[]) { CWF::CppWebApplication server(argc, argv, "/PATH_TO_EXAMPLE/server/"); server.addController("/countries"); return server.start(); }

The only thing you need to do in the other controllers that use CWF::SqlDatabaseStorage storage is to use the "extern" keyword: extern CWF::SqlDatabaseStorage storage;

Do not use QSqlDataBase because you can't use it across threads. Use CWF::SqlDatabaseStorage, it's going to create one connection per thread and reuse it while the thread is alive.