CakePHP Authentication 3快速入门是否会自动生成add.php?
解决CakePHP Authentication入门中UsersController::add()视图缺失问题
- 这是指南的正常情况,官方快速入门指南并没有包含创建add视图的步骤。
- 指南核心是演示认证系统的配置流程,用户注册的视图和完整注册逻辑需要你自行补充:
- 在项目的
templates/Users目录下新建add.php文件(如果该目录不存在,需要手动创建) - 编写用户注册表单,推荐使用CakePHP的
FormHelper快速构建,示例代码如下:
- 在项目的
// templates/Users/add.php echo $this->Form->create($user); echo $this->Form->control('username', ['label' => '用户名']); echo $this->Form->control('email', ['label' => '邮箱']); echo $this->Form->control('password', ['label' => '密码']); echo $this->Form->button('完成注册'); echo $this->Form->end();
- 同时完善
UsersController里的add方法,处理表单提交后的用户数据保存(注意密码需要哈希处理):
// src/Controller/UsersController.php public function add() { $user = $this->Users->newEmptyEntity(); if ($this->request->is('post')) { $user = $this->Users->patchEntity($user, $this->request->getData()); $user->password = $this->Authentication->getPasswordHasher()->hash($user->password); if ($this->Users->save($user)) { $this->Flash->success('用户注册成功,请登录'); return $this->redirect(['action' => 'login']); } $this->Flash->error('注册失败,请检查输入内容后重试'); } $this->set(compact('user')); }
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

