PHP useful MySQL operation class (Design pattern Interpretation one) _php tutorial

Source: Internet
Author: User
To use PHP to operate a database is very simple, the corresponding entry of the phper can do, but when dealing with a large number of table operations, we are tired of many MySQL statements, so we are eager to wrap up a lot of database operations. So a database object map appears.

First we create a new interface.

singleton.class.php
[PHP]
/**
* @author Tomyjohn
* @link
* @license
* @version 1.0
* @copyright Copyright Tomyjohn-tomyjohn.gicp.net
* @package Singleton
*/
/**
* Database Objects
*/
Interface singleton{

/**
* Generate Database objects
* @returns Object data object;
* @access Public
*/
public static function getinstance ();
}

Create a new abstract class that abstracts all the databases concisely in 5 ways.
db.class.php
[PHP]
/**
* @author Tomyjohn
* @link
* @license
* @version 1.0
* @copyright Copyright Tomyjohn-tomyjohn.gicp.net
* @package DB
*/
/**
* Abstract DB Class
*/
Abstract class db{

/**
* Factory mode
* @param string $type SQL type
* @returns Object
* @access Public
*/
public static function Factory ($type) {
return Call_user_func (Array ($type, ' getinstance '));
}
/**
* Execute SQL statement
* @param string $query SQL statement
* @return object resource or false;
* @access Public
*/
Abstract Public Function execute ($query);
/**
* Gets the array returned by the SQL statement
* @param string $query SQL statement
* @return object resource or false;
* @access Public
*/
Abstract public Function Get_array ($query);
/**
* Gets the execution ID of the previous statement
* @param string $query SQL statement
* @return integer number or false;
* @access Public
*/
Abstract public Function insert_get_id ($query);
/**
* Convert special characters
* @param string $string
* @return string processed by string
* @access Public
*/
Abstract Public Function clean ($string);
}

Believe to see here, will think of that Call_user_func method how to use, don't worry, look down
mysql.class.php
[HTML]
/**
* @author Tomyjohn
* @link
* @license
* @version 1.0
* @copyright Copyright Tomyjohn-tomyjohn.gicp.net
* @package DB
*/
/**
*mysql database Objects
*/
Class MySQL extends DB implements singleton{

/**
* @var $instance Object
* @access Current class
*/
protected static $instance = NULL;
/**
* @var $link Resource
* @access Current class
*/
protected $link;

/**
* DB Instance
* @return $self:: Instance Object
*/
public static function getinstance () {
if (Is_null (self:: $instance)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}

/**
* Constructor
*/
protected function __construct () {
Global $current _conf;
$user = $current _conf[' DBUSER ');
$pass = $current _conf[' dbpwd ');
$host = $current _conf[' dbhost ');
$db = $current _conf[' DBNAME ');

$this->link = mysql_connect ($host, $user, $pass);

Mysql_set_charset ($current _conf[' Dbcharset '), $this->link);
mysql_select_db ($DB);
}

/**
* Convert special characters
* @param string $string
* @return string processed by string
* @access Public
*/
Public function Clean ($string) {
Return mysql_real_escape_string ($string, $this->link);
}

/**
* Execute SQL statement
* @param string $query SQL statement
* @return object resource or false;
* @access Public
*/
Public function Execute ($query) {
Return mysql_query ($query, $this->link);
}
/**
* Gets the execution ID of the previous statement
* @param string $query SQL statement
* @return integer number or false;
* @access Public
*/
Public Function insert_get_id ($query) {
$this->execute ($query);
Return mysql_insert_id ($this->link);
}
/**
* Gets the array returned by the SQL statement
* @param string $query SQL statement
* @return object resource or false;
* @access Public
*/
Public Function Get_array ($query) {
$result = $this->execute ($query);
$return = Array ();
if ($result) {
while ($row = Mysql_fetch_array ($result, Mysql_assoc)) {
$return [] = $row;
}
}
return $return;
}
}

Current_conf This array is my project, in fact, you can also use your database user name and password instead, read this I think you should also be clear, inherit DB and then implement Singleton interface after this class, actually can also be used to mssql,oracl, as well as other databases, But with this in light, we can only make the operational database that way.

[HTML] View plaincopy
$connection = db::factory (' mysql ');
$sql = "SELECT * FROM table";
$value _array = $connection->get_array ($sql);
[HTML] View plaincopy
Print_r ($value _array);
This solves the extension, resolves some repetitive operations, but is not very convenient, we should go further, so that the database table with the object representation, that is, the database mapping

dao.class.php

[HTML]
Class dao{
/**
* @var $values array to store database objects
* @access Current class
*/
Protected $values = Array ();

/**
* @var $suffix array to store database objects
* @access Public
*/
Public $suffix = ';

/**
* Constructor
*/
Public function __construct ($qualifier = null) {
Global $current _conf;
$this->suffix = $current _conf[' Dbsuffix ');

if (!is_null ($qualifier)) {
$conditional = Array ();

if (Is_numeric ($qualifier)) {
$conditional = array (' id ' = = $qualifier);
}
else if (Is_array ($qualifier)) {
$conditional = $qualifier;
}
else{
throw new Exception (' Invalid type of qualifier given! ');
}

$this->populate ($conditional);
}
}

Public Function __set ($name, $value) {
$this->values[$name] = $value;
}

Public Function __get ($name) {
if (Isset ($this->values[$name])) {
return $this->values[$name];
}
else{
return null;
}
}

/**
* Parse the parameters of the instance
* @param $conditional obj
*/
protected function Populate ($conditional) {
$connection = db::factory (' mysql ');

$sql = "Select * FROM {$this->suffix}{$this->table} WHERE";
$qualifier = ";

foreach ($conditional as $column = = $value) {
if (!empty ($qualifier)) {
$qualifier. = ' and ';
}
$qualifier. = "' {$column} ' = '". $connection->clean ($value). "' ";
}

$sql. = $qualifier;
$value _array = $connection->get_array ($sql);

if (!isset ($value _array[0])) {
$value _array[0] = array ();
}

foreach ($value _array[0] as $key = = $value) {
$this->values[$key] = $value;
}
}

/**
* Save Data
*/
Public Function Save () {
if (! $this->id) {
$this->create ();
}
else{
return $this->update ();
}
}

/**
* Add Data www.2cto.com
*/
Public Function Create () {
$connection = db::factory (' mysql ');

$sql = "INSERT into {$this->suffix}{$this->table} ('";
$sql. = Implode ("', '", Array_keys ($this->values));
$sql. = "') VALUES ('";

$clean = Array ();
foreach ($this->values as $value) {
$clean [] = $connection->clean ($value);
}

$sql. = Implode ("', '", $clean);
$sql. = "')";

$this->id = $connection->insert_get_id ($sql);
}

/**
* Update Data
* @return Returns the result of the action performed
*/
Public Function Update () {
$connection = db::factory (' mysql ');

$sql = "UPDATE {$this->suffix}{$this->table} set";

$updates = Array ();
foreach ($this->values as $key = + $value) {
if ($key! = ' id ') {
$updates [] = "' {$key} ' = '". $connection->clean ($value). "'";
}
}

$sql. = Implode (', ', $updates);
$sql. = "WHERE id={$this->id}";

Return $connection->execute ($sql);
}
/**
* Delete Data
* @return Returns the result of the action performed
*/
Public Function Delete () {
$connection = db::factory (' mysql ');

$sql = "DELETE from {$this->suffix}{$this->table} WHERE";
$qualifier = ' id= '. $this->id;

$sql. = $qualifier;
Return $connection->execute ($sql);
}

/**
* Object to Group
* @return Array
*/
Public Function Object_to_array () {
return $this->values;
}

}

If you see this, I believe everyone will want to inherit this class. Yes, if you inherit this class, then each record can become an object, and it can be handled in an object-oriented manner.

I write a

News.dao.class


Class News extends dao{
protected $table = __class__;

}


Author: Tomyjohn

http://www.bkjia.com/PHPjc/478158.html www.bkjia.com true http://www.bkjia.com/PHPjc/478158.html techarticle to use PHP to operate a database is very simple, the corresponding entry of the phper can do, but in dealing with a large number of table operations, we are tired of many MySQL statements, so we are anxious ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.