Home  >  Article  >  Backend Development  >  PHP Design Pattern Series - Data Access Object Pattern_PHP Tutorial

PHP Design Pattern Series - Data Access Object Pattern_PHP Tutorial

PHP中文网
PHP中文网Original
2016-07-13 17:51:54849browse

Data Access Object Pattern

The Data Access Object Pattern describes how to create objects that transparently access data sources.
Scene design
Design a BaseDao base class to implement some basic query, insert, and update methods for database operations
In the actual use process, by inheriting BaseDao, you can directly call the database operation methods of the base class
Code: BaseDao database operation base class
[php]

<?php 
//数据访问对象模式 
 
//将数据库访问层脱离出来 作为公用的访问接口,方便用户开放,是php中常用的一种设计模式 
 
class BaseDao { 
    private $db; 
     
    public function __construct($config) {  
        $this->db = mysql_connect($config[&#39;user&#39;], $config[&#39;pass&#39;], $config[&#39;host&#39;]); 
        mysql_select_db($config[&#39;database&#39;], $this->db); 
    } 
     
    public function query($sql) { 
        return mysql_query($sql, $this->db); 
    } 
}


Code: UserDao user data table data operation, inherits BaseDao
[php] www.2cto.com

<?php 
include("UserDao.php"); 
class UserDao extends BaseDao { 
    public function addUser() { 
        $sql = "INSERT INTO user (username) VALUES (&#39;initphp&#39;)"; 
        return $this->query($sql); 
    } 
} 
 
$UserDao = new UserDao; 
$UserDao->addUser();


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn