【问题标题】:db class function not recogniseddb 类函数无法识别
【发布时间】:2015-04-16 08:54:53
【问题描述】:

得到一个:

致命错误:在第 27 行调用未定义的方法 UsersController::select() application/models/User.php

看起来 UsersController 没有将选择函数发送到我在库文件夹中的 db.class.php。

正在加载 db.class.php,但在这种情况下没有。

UserController.php 类中的代码是:

class User extends Model
{        

/**
 * Login method
 *
 * @todo: update last_login_time
 * @todo: add hashing
 */
public function user_login() {

    $username = $_POST['data']['User']['username'];
    $password = $_POST['data']['User']['password'];


    $bind = array(
        ":username" => $username,
    );
    $result = $this->select("users", "username = :username", $bind);

    //Check the password returned from the db against the password entered
    if (Bcrypt::checkPassword($password, $result[0]['password']) == true) {
        Session::init();

        Session::set('user_logged_in', true);
        Session::set('user_id', $result[0]['id']);
        Session::set('user_name', $result[0]['username']);
        Session::set('user_permission', $result[0]['permission']);
        Session::set('user_role', $result[0]['role']);

        return true;
    } else {
        return false;
    }
}


/**
 * Log out process, deletes cookie, deletes session
 *
 * @todo implement rememberme cookie
 */
public function logout()
{
    // set the remember-me-cookie to ten years ago (3600sec * 365 days * 10).
    // that's obviously the best practice to kill a cookie via php
    // @see http://stackoverflow.com/a/686166/1114320
    //setcookie('rememberme', false, time() - (3600 * 3650), '/', COOKIE_DOMAIN);

    Session::init();
    // delete the session
    Session::destroy();
}

}

在 db.class.php 中选择函数

public function select($table, $where="", $bind="", $fields="*") {
    $sql = "SELECT " . $fields . " FROM " . $table;
    if(!empty($where))
        $sql .= " WHERE " . $where;
    $sql .= ";";
    return $this->run($sql, $bind);
}

我认为这可能是对 $this->select() 的引用,但我正在学习。

【问题讨论】:

  • 如果您发布有关特定错误的帖子,您必须包括完整的错误消息(带有行号)以及至少该行及其前一行的代码。
  • 这个错误告诉我的是 UserController 类没有一个名为 select() 的方法。是 Laravel 吗?
  • select() 方法在哪里?
  • @N.DeNisse - 这是 php 蛋糕。
  • @JasonMcCreary - 刚刚添加。

标签: php model-view-controller


【解决方案1】:

此错误的原因是select(),据我所知,它不是UserModelModel 层次结构中的其他父级的方法。

而是在 db.class.php 中。

鉴于目前的代码,我建议将一个DB对象注入User/Model,然后直接委托给这个对象。

例如:

class Model {
    public function __construct(DB $db) {
        $this->db = $db;
    }
}

然后,要解决错误,请在User 中执行:

$result = $this->db->select("users", "username = :username", $bind);

注意:这是不完整的。所以你需要填写一些空白。既然你正在学习,我建议阅读:

另外,.class.php 是 PHP 4 中使用的旧命名约定。不要这样做。相反,请遵循 PSR-4 命名约定。

【讨论】:

  • 好的 - 试试看,我可能需要再看书哈哈
  • 看到你更新的评论,如果这应该是 CakePHP,这段代码不符合他们的约定。
  • 谢谢 - 我很难理解它,但学习都是一样的。
猜你喜欢
  • 1970-01-01
  • 2011-07-10
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
相关资源
最近更新 更多