What Am I going to talk about?
A few months ago, I was developing an MVC web framework in C++, mostly inspired by the Ruby on Rails framework. Apart the fact that, like most of the side projects, it’s been a while I haven’t coded any line for this project, it leads me to some interesting problematics.
The problematic that is interesting here and that can introduce this article concerns the configuration of the routes. Indeed, one of the most important feature of an MVC web framework is to configure some routes that the client can request. Each route forward the request to a specific action of a controller.
For example, we can have a
/articles route which is linked to the
index action of the
articles controller. When the client requests this path,
articles_controller::index is called and returns a list of the articles.
For my MVC project, I wanted it to be easy to configure the routes and to hide this part from the user. I didn’t want the developer to declare his routes by writing C++ code: it would have been less convenient, less readable and maybe less maintainable.
1 2 3 4 5
Instead, I’d prefer to have a simple JSON configuration file where the developer can easily declare its routes.
1 2 3 4 5 6 7 8 9 10 11
As you can see, by using this simple JSON configuration file, it would be really easy and readable to declare routes and to associate them to a specific action of a controller.
This idea directly leads us to the topic of this article: how to convert the string
articles#index to the call
ArticlesController(...).index(...). The answer is Reflection.
Reflection is, in some languages, a part of the language that gives us the ability to retrieve information from a type or a method, dynamically, at runtime. And moreover, reflection lets us instantiate an object from a string containing the class name or call a method from a string containing its name. For example, in Ruby on Rails, we can do
"SomeClass".constantize.new.send "some_method" and it will call
SomeClass::some_method at runtime.
However, there is no reflection engine in C++, even in the latest version. So, I had to build my own reflection engine and I’m going to explain how I did in this paper.