如何使用用户名作为路径

时间:2018-10-29 13:00:25

标签: php url-routing

我想从每个用户那里获取用户名,并将其用作其个人资料的路径。因此路径应为localhost:8080 / user,但我无法使其正常工作。尽管我可以使其与id一起使用。

谢谢您的帮助! :)

routes.json

":username": {
    "controller": "User",
    "method": "getProfileByUsername",
    "params": {
      "username": "string"
    }
  }

UserController.php

public function getProfileByUsername($username)
    {
        $userModel = new UserModel();

        try {
            $user = $userModel->getProfileByUsername($username);
        } catch (\Exception $e) {
            $properties = ['errorMessage' => 'User not found!'];
            return $this->render('views/error.php', $properties);
        }

        $properties = ['user' => $user];
        return $this->render('views/profile.php', $properties);
    }

UserModel.php

public function getProfileByUsername($username)
    {
        $query = 'SELECT * FROM users WHERE username = :username';
        $sth = $this->db->prepare($query);
        $sth->execute(['username' => $username]);

        $users = $sth->fetchAll(PDO::FETCH_CLASS, self::CLASSNAME);
        if (empty($users)) {
            throw new NotFoundException();
        }


        return $users[0];
    }

1 个答案:

答案 0 :(得分:0)

您必须配置Web服务器以将此类路径重定向到类似getuser.php?user=(user)的路径-具体操作方法取决于您的Web服务器。

在Apache 2上,可以使用.htaccess来完成。我建议将用户放在诸如/user/之类的子文件夹中,因为这将使重定向更加容易。

RewriteEngine On
RewriteRule ^user/(.*)$ ./getuser.php?user=$1