如何告诉控制器要调用哪个视图?
我的 Controller 类中有一个名为 handlePathChange() 的虚拟函数。
它检查当前 URL 并应为其分派正确的视图。
这是我到目前为止的代码:
void Controller::handlePathChange()
{
if ( app->internalPathMatches(basePath) )
{
string path = app->internalPathNextPart(basePath);
if ( path.empty() ) // If it's empty it is known that the index of the controller should show up
index();
// else if ( path == ?? ) each controller has it's own routes
// call_some_unknown_function();
}
}
我怎样才能概括这一点?
我正在考虑两个选项:
- 调用一个名为dispatch() 的纯虚函数,它将匹配派生类中正确函数的正确路径。该解决方案违反了 DRY,因为基本上您将一遍又一遍地编写相同的代码。
- 创建 std::function 的哈希映射,但如果 url 的一部分是参数,则将找不到视图。所以这个选项还不够好。
有什么想法吗?
I have a virtual function that is called handlePathChange() in my Controller class.
It checks the current URL and should dispatch the right view for it.
Here's the code I have so far:
void Controller::handlePathChange()
{
if ( app->internalPathMatches(basePath) )
{
string path = app->internalPathNextPart(basePath);
if ( path.empty() ) // If it's empty it is known that the index of the controller should show up
index();
// else if ( path == ?? ) each controller has it's own routes
// call_some_unknown_function();
}
}
How can I generalize this?
I was thinking about two options:
- Call a pure virtual function called dispatch() that will match the right path to the right function in the derived class. This solution violates DRY as basically you will write the same code over and over again.
- Create a hash maps of std::function but then if a part of the url is a parameter then the view won't be found. So that option isn't good enough.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道您的文章使用了 C++ 示例,但如果您不介意阅读一些 C#,Scott Guthrie 的这篇文章很好地概述了 ASP.NET MVC 框架如何实现其路由:
http://weblogs.asp.net /scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
我想您会发现这篇文章非常有帮助。以一种过于简化的方式,它类似于您的选项#2,但它总是检查参数。如果未提供该参数,则它使用相同的路由规则,但提供“默认”值并将请求发送到正确的视图。该策略避免了您提到的问题,即如果指定了参数,则无法找到适当的视图。
希望这有帮助。
I realize your post uses a c++ example, but if you don't mind reading some c#, this article by Scott Guthrie is a great overview of how the ASP.NET MVC framework implements its routing:
http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
I think you will find that article very helpful. In an overly simplified sort-of-way, it is similar to your option #2, yet it always checks for a parameter. If the parameter is not provided, it uses the same routing rule, but provides a "default" value and sends the request to the correct view. That strategy avoids the problem you mention where you can't find the appropriate view if the parameter is specified.
Hope this helps.