Php 尝试验证数据库中已存在的电子邮件时出现问题
为了学习,我正在用php构建自定义mvc框架。当我试图用数据库中已经存在的邮件提交表单时,我的验证会阻止我这样做,相反,我会出现以下错误:Php 尝试验证数据库中已存在的电子邮件时出现问题,php,validation,oop,model-view-controller,Php,Validation,Oop,Model View Controller,为了学习,我正在用php构建自定义mvc框架。当我试图用数据库中已经存在的邮件提交表单时,我的验证会阻止我这样做,相反,我会出现以下错误: Fatal error: Uncaught Error: Call to a member function findUserByEmail() on null in C:\xampp\htdocs\gacho\App\Controllers\UsersController.php: UsersController.php <?php namespa
Fatal error: Uncaught Error: Call to a member function findUserByEmail() on null in C:\xampp\htdocs\gacho\App\Controllers\UsersController.php:
UsersController.php
<?php
namespace App\Controllers;
use App\Models\User;
use Core\Controller;
class UsersController extends Controller
{
public function __construct($controller, $action)
{
parent::__construct($controller, $action);
$this->userModel = $this->load_model('User');
}
public function registerAction()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = [
'email' => trim($_POST['email']),
];
}
if (empty($data['email'])) {
$data['email_err'] = "Please enter your email!!!";
} else {
if ($this->userModel->findUserByEmail($data['email'])) {
$data['email_err'] = "Email is already taken!";
}
}
}
我认为您需要在$this->UserModel中访问您的模型,因为User
被传递到load\u model方法中。问题是,在userscocontroller的\uu构造中,您有:
$this->userModel = $this->load_model('User');
因此,将load\u model
方法的返回值指定给userModel
属性。
load\u model
方法不会返回任何内容,因此$this->userModel
始终设置为NULL
,无论load\u model
是否成功
您应该只返回新的$modelPath()如果要通过返回值将其指定给属性,请在load_model
中选择code>
还添加抛出新异常($modelPath.'notfound')
在load_model
方法的末尾,确保它确实加载了模型,而不是只是默默地找不到它
请注意,$this->userModel
与$this->userModel
(区分大小写)和$modelPath='App\Models\\\'不同$模型代码>-为什么在应用程序之后和两个模型之后 我试过了,但我不太明白你的意思。你能再解释一下吗?你能在UserController
Yes中将$this->userModel更改为$this->userModel吗。我就是这么做的,但它显示了同样的错误。
<?php
namespace Core;
class Controller
{
protected $_controller;
protected $_action;
public $view;
public function __construct($controller, $action)
{
$this->_controller = $controller;
$this->_action = $action;
$this->view = new View();
}
protected function load_model($model)
{
$modelPath = 'App\Models\\' . $model;
if (class_exists($modelPath)) {
$this->{$model.'Model'} = new $modelPath();
}
}
}
$this->userModel = $this->load_model('User');