【发布时间】:2018-10-30 09:31:53
【问题描述】:
所以在php中你可以像做动态路由
class Route
{
public function homePage ()
{
echo 'You are on the home page'
}
public function otherPage ()
{
echo 'You are on some other page'
}
}
class Route2
{
public function homePage ()
{
echo 'You are on the home page'
}
public function otherPage ()
{
echo 'You are on some other page'
}
}
// when you get the url like www.domain/route/other-page, with some regex operation you get out as string 'route' and 'other-page' from the route transform it to 'Route' and 'ohterPage' and fill them into the $controller and action variables and you just call:
$controller->$action();
// and it will call Route->otherPage() which will serve up the requested template
当您获得像 www.domain/route/other-page 这样的 url 时,通过一些正则表达式操作,您会从路由中以字符串 'route' 和 'other-page' 的形式将其转换为 'Route' 和 'ohterPage'并将它们填充到 $controller 和 $action 变量中,您只需调用 '$controller->$action();'它会调用 Route->otherPage() 来提供请求的模板
这是一个很好的解决方案,因为当你有 40 种不同的操作,比如提供模板和各种 get 和 post 请求时,你可以通过添加 5 个路由来处理它,但为此你需要动态引用对象和方法像上面......有什么方法可以在javascript中实现这一点?
谢谢
【问题讨论】:
-
“动态”是指通过类名实例化对象的能力吗?
-
所以动态我的意思是,在你从 url 中获取控制器和操作之后,可以说这是 url:www.website.com/user/log-in 并且你提取了 'user ' 进入一个变量,让我们说 'let controller' 和 'log-in' 进入名为 'let action' 的变量,然后你可以通过控制器变量的值来实例化控制器对象,并通过值调用控制器上的方法动作变量的...在php中你可以像'let Controller ='user';让行动='登录';让控制器 = 新控制器();控制器.action();这将调用 user.logIn();
标签: javascript node.js class routing dynamic-routing