尝试验证数据库中已存在的电子邮件时出现问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试验证数据库中已存在的电子邮件时出现问题相关的知识,希望对你有一定的参考价值。

我正在php中构建自定义mvc框架以便学习,当我尝试使用已存在于数据库中的邮件提交我的表单时,我的验证应该阻止我这样做,而是我收到此错误:

Fatal error: Uncaught Error: Call to a member function findUserByEmail() on null in C:xampphtdocsgachoAppControllersUsersController.php:

UsersController.php

<?php
namespace AppControllers;

use AppModelsUser;
use CoreController;

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!";
                }
          }
    }

user.php的

<?php
namespace AppModels;

use CoreDatabase;

class User
{
    private $db;

    public function __construct()
    {
        $this->db = new Database();
    }

    public function findUserByEmail($email)
    {
        $this->db->query('SELECT * FROM users WHERE email = :email');
        $this->db->bind(':email', $email);
        $row = $this->db->single();
        if ($this->db->rowCount() > 0) {
            return true;
        } else {
            return false;
        }
    }
}

Controller.php这样:

<?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 = 'AppModels\' . $model;
        if (class_exists($modelPath)) {
            $this->{$model.'Model'} = new $modelPath();
        } 
    }
}

我认为错误是关于$ this-> userModel,但我被卡住了,任何帮助都表示赞赏。

答案

问题是在USERController的__construct中你有:

$this->userModel = $this->load_model('User');

因此,您为userModel属性指定了load_model方法的返回值。 load_model方法不返回任何东西所以$this->userModel总是设置为NULL,如果load_model成功与否则无关紧要。

如果你想通过返回值将它分配给一个属性,你应该只在return new $modelPath();中使用load_model

还要在throw new Exception($modelPath. 'not found');方法的末尾添加load_model,以确保它确实加载了模型,而不是只是无声地找到它。

请注意,$this->userModel$this->UserModel(区分大小写)和$modelPath = 'AppModels\' . $model;不同 - 为什么在App之后,两个在模型之后?

另一答案

我认为您需要在$ this-> UserModel中访问您的模型,因为User已传递到load_model方法。

以上是关于尝试验证数据库中已存在的电子邮件时出现问题的主要内容,如果未能解决你的问题,请参考以下文章

尝试在 Laravel 中设置身份验证时出现“ReflectionException Function () 不存在”

验证电子邮件地址时出现 jQuery 错误

通过 PHPMailer 发送电子邮件时出现身份验证错误

访问片段的子视图时出现空指针异常

尝试访问 Kotlin 片段中的视图时出现 NullPointerException

错误3004:从行开始映射片段时出现问题