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

问题描述 投票:-1回答:2

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

user.php的

<?php
namespace App\Models;

use Core\Database;

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

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

php validation oop model-view-controller
2个回答
1
投票

问题是在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 = 'App\Models\\' . $model;不同 - 为什么\在App之后,两个\在模型之后?


-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.