如何在FOSUserBundle中实现其他用户的公开个人资料访问?
解决FOSUserBundle公开其他用户个人资料的问题
我明白你的问题了——你现在的问题是点击广告作者的用户名时,总是跳转到当前登录用户的资料页,这大概率是因为你在生成链接或者处理请求的时候,错误地使用了当前登录用户(app.user)的信息,而不是广告所属用户(ad.user)的信息。下面我一步步帮你解决:
1. 先修正模板里的用户名链接
首先检查你展示广告的Twig模板,确保点击用户名时,传递的是广告作者的用户名(或ID),而不是当前用户的。比如:
<!-- 错误的写法(会跳转到当前用户) --> <a href="{{ path('fos_user_profile_show') }}">{{ ad.user.username }}</a> <!-- 正确的写法(传递广告作者的用户名) --> <a href="{{ path('public_user_profile', {'username': ad.user.username}) }}">{{ ad.user.username }}</a>
这里的public_user_profile是我们接下来要创建的自定义路由,用来处理公开资料的请求。
2. 创建公开用户资料的路由
你需要在config/routes.yaml(或者用注解路由)里添加一个新的路由,指向专门的控制器方法:
# config/routes.yaml public_user_profile: path: /user/{username} controller: App\Controller\UserController::showPublicProfile methods: GET
如果用注解路由的话,在控制器里直接添加:
// src/Controller/UserController.php use Symfony\Component\Routing\Annotation\Route; /** * @Route("/user/{username}", name="public_user_profile", methods={"GET"}) */ public function showPublicProfile(string $username, UserManagerInterface $userManager) { // 代码见下一步 }
3. 编写控制器方法获取目标用户
在控制器里,根据传递的用户名从数据库获取对应的用户对象,然后渲染公开资料模板:
// src/Controller/UserController.php use FOS\UserBundle\Model\UserManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class UserController extends AbstractController { public function showPublicProfile(string $username, UserManagerInterface $userManager) { // 根据用户名获取用户 $user = $userManager->findUserByUsername($username); // 如果用户不存在,抛出404 if (!$user) { throw new NotFoundHttpException('该用户不存在'); } // 渲染公开资料模板 return $this->render('user/public_profile.html.twig', [ 'target_user' => $user, ]); } }
4. 创建公开资料的模板
复制FOSUserBundle的profile模板(通常在vendor/friendsofsymfony/user-bundle/Resources/views/Profile/show.html.twig),然后修改成只展示公开字段的版本,保存到templates/user/public_profile.html.twig:
{# templates/user/public_profile.html.twig #} {% extends 'base.html.twig' %} {% block body %} <h1>{{ target_user.username }}的个人资料</h1> {# 只展示公开允许的字段,比如昵称、简介等,不要显示邮箱、密码等敏感信息 #} <p>昵称: {{ target_user.username }}</p> {% if target_user.profile.bio %} <p>简介: {{ target_user.profile.bio }}</p> {% endif %} {# 其他公开字段... #} {% endblock %}
最后检查权限(可选)
如果你需要限制某些用户的公开资料访问(比如仅登录用户可见),可以在控制器方法里添加权限验证:
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');
这样修改后,点击广告作者的用户名就会跳转到该用户的公开个人资料页,而不是当前登录用户的页面了。
内容的提问来源于stack exchange,提问作者Lilidevmart
相关产品推荐
相关产品推荐

