doushi1929 2013-07-16 19:36
浏览 26
已采纳

尝试在PDO之上定义模型类并且失败很长时间

I'm trying to build a small, seemingly simple app in pure php (can't use any framework or fancy tools such as orms).

I got started by defining object representing my models. My idea is to have a Model base class, which would hold a static pdo instance to access the database, and two "concrete" model classes inheriting from it and implementing the custom method they'll need.

Well, boy am i rusty in PHP. It's also the first time i'm doing actual oop with it (i've done enough of it in other languages (C# and python, mainly) to understand how it's supposed to work, but some subtleties might very well elude me.

If anyone cares to help, here's what i have so far:

<?php
/**
 * Base model class, handling basic db connection
 */
Class Model {

    protected static $db;

    public static function initDb() {
        self::$db = new PDO(DB_CONNECTION_STRING, DB_USER, DB_PSWD);
    }

    protected function _prepare_request($sqlstmnt) {
        return self::$db->prepare($sqlstmnt);
    }

}

Model::initDb();

/**
 * Model class for Category objects
 **/
Class Categorie extends Model {

    private $request_getSingle = NULL;

    public function __contruct() {
        $this->request_getSingle = $this->_prepare_request(
            "SELECT * FROM categorie WHERE cat_id = :id;"
        );
    }   

    public function getById($id) {
        $poop = $this->request_getSingle->execute(array(':id' => $id));
        $res = $poop->fecthAll();
        print_r($res);
    }

}

// Debug tests:
$c = new Categorie();
var_dump($c);
$c->getById('1');
print_r($c);
echo 'done';
?>

Seems like my query objects are not initialized properly - Here's what i get when i run that silly debug code:

object(Categorie)#3 (1) { ["request_getSingle":"Categorie":private]=> NULL } 
Fatal error: Call to a member function execute() on a non-object in /home/raphi/dev/naoned-test/models/categories.php on line 18 
Call Stack: 
    0.0003 648192 1. {main}() /home/raphi/dev/naoned-test/models/categories.php:0 
    0.0011 661784 2. Categorie->getById() /home/raphi/dev/naoned-test/models/categories.php:27

I have NO idea what exactly is going wrong. I might be using static variables wrong, or miss something about how PDO works.

Hope that's clear enough, and thank to anyone willing to help (there might be somme silly errors here and there caused by helpless hacking around).

EDIT: After hacking around, turns out that if i call the PDO prepare, execute, etc... methods within getById, everything works fine. But why can't i keep the prepared SQL statement as an instance variable ? Having to call prepare each time i want to access it seems to defeat its purpose...

EDIT: Well... This seems fixed, but i still don't understand. I've replaced my request_getSingle variable by an array, which contains several prepared statements (which is what i planned to do eventually anyway...) and everything works fine.

I don't get it. If i store them in an array, they can be accessed from the class's other methods, but if i store them as regular attributes, they can't ?

If anyone has some idea of what's going on, i'm still interested...

  • 写回答

1条回答 默认 最新

  • douyanxing6054 2013-07-16 20:21
    关注

    try this:

    Class Model extends PDO {
    

    I have a similar class that writes custom functions on top of PDO. I think you are trying to do something similar here. This is how the initial code in my class looks like:

    class MySQLDB extends PDO{
        public function __construct($dsn, $user="", $pass="") {
            $options = array(
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                PDO::ATTR_PERSISTENT => true, 
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            );
    
            try {
                parent::__construct($dsn, $user, $pass, $options);
            } catch (PDOException $err) {
                die($e->getMessage());
            }
        }
    }
    

    After you do that, you should be able to use all the PDO functions through this class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序