目前,我在一个小网站上。用户登录后,他将被重定向到他的个人资料页面。到目前为止,我已经使用以下代码路由了URL:
public function route($uri)
{
$path = $uri;
switch ($path) {
case '/':
return new FrontPageController;
case '/login':
return new LoginFormPageController;
case '/action/login':
return new LoginController;
case '/register':
return new RegisterFormPageController;
case '/action/register':
return new RegisterController;
case '/Profile/' . :
return new ProfilePageController;
case '/logout':
return new LogoutController();
default:
echo 'error';
}
}
但是我该如何通过个人资料页面来做到这一点呢?配置文件 uri 应如下所示:http://example.com/Profile/USERNAME,并且应该可以从任何地方访问。我试图用
case '/Profile/' . $_SESSION['username']:
return new ProfilePageController;
但是只有登录的用户才能看到自己的页面。如何识别我的路由器,在配置文件/输入用户名之后?登录个人资料页面后我该如何前往?我可以路由到配置文件/并手动添加用户名吗?
顺便说一句:我使用 NGINX 请不要说修改 .htaccess 之类的话
您可以将大小写"/配置文件/"块更改为如下所示的内容:
// check if route matches a pattern. preg_match return true if any matches found
case preg_match('/'/Profile'/([a-z0-9]+)/', $path, $matches):
// we remove the first element
$params = array_shift($matches);
// pass params to construct
return new ProfilePageController($params);
现在回到控制器中
class ProfilePageController
{
public function __construct($params)
{
$userid = $params[0];
}
}