/** * 获取对象唯一实例 * * @param void * @return object 返回本对象实例 */ public static function getInstance($controller) { if (!self::$_instance instanceof self) { self::$_instance = new self($controller); } return self::$_instance; }
/** * Model构造函数 * * @param string $controllerName 控制器名 * @return void */ public function __construct($controller) { if (!is_object($controller)) { throw new TM_Exception("TM_Model: controller is empty"); } $this->controller = $controller; $this->model = TM_Model::getInstance($controller); $this->db = $this->model->getDb(); $this->db->query("set names " . $this->config['DataBase']['charset']); }
/** * 数据库访问Action * * 访问URL:http://localhost/?c=index&a=db * http://localhost/index/db * * @return void */ public function dbAction() { try { //直接连接数据库 $driver = $this->config['DataBase']['driver'] == '' ? "DB_Mysql" : $this->config['DataBase']['driver']; $class = TM_PREFIX . "_" . $driver; $dbConfig = array("host" => $this->config['DataBase']['host'], "user" => $this->config['DataBase']['user'], "pwd" => $this->config['DataBase']['pwd'], "db" => $this->config['DataBase']['db']); $db = new $class($dbConfig); //从Model访问数据库 $model = TM_Model::getInstance($this); $db = $model->getDb(); //设置数据库编码 $db->query("set names " . $this->config['DataBase']['charset']); //建立一个数据表 $db->query("CREATE TABLE user (\n\t\t\t\t\t\t`id` INT( 10 ) NOT NULL AUTO_INCREMENT ,\n\t\t\t\t\t\t`name` VARCHAR( 32 ) NOT NULL ,\n\t\t\t\t\t\t`email` VARCHAR( 32 ) NOT NULL ,\n\t\t\t\t\t\tPRIMARY KEY ( `id` ) \n\t\t\t\t\t\t) ENGINE = MYISAM ;\n\t\t\t\t"); //插入一条记录 $arrInsert = array("name" => 'heiyeluren', "email" => '*****@*****.**'); $db->insert($arrInsert, "user"); //更新记录 $arrUpdate = array("name" => 'test', "email" => '*****@*****.**'); $db->update($arrUpdate, "name='heiyeluren'", 'user'); //统计记录数 $total = $db->count(array('name' => 'test'), array(), 'user'); //读取所有记录 $list = $db->getAll("select * from user"); //设置展现模板数据 $this->title = "数据库访问展现页"; $this->total = $total; $this->list = $list; //设置模板进行展现 $this->render('db.php'); } catch (TM_Exception $e) { echo "db action error: " . $e->getMessage(); } }