当前位置: 编程技术>php
本页文章导读:
▪php xml-rpc远程调用
代码如下:<?php /* 从网上找来的XML-RPC库,对于开发小型的外部通讯接口很有用 */ function & XML_serialize($data, $level = 0, $prior_key = NULL){ #assumes a hash, keys are the variable names $xml_serialized_string = "";.........
▪php 设计模式之 工厂模式
本人常用mysql数据库,所以程序只写了mysql的数据库操作类。希望各位高手把另外的类写全,最好能发一份给我。 db_mysql.php继承db.php接口,具体实现数据库操作的各种方法 ,如果你确定你的.........
▪php 设计模式之 单例模式
小船类boat.php 代码如下:<?php class boat { private static $instance=null; private $skipper; private $personNum=0; private $passengers=array(); private function __construct() { } public static function getInstance(){ if (self::$instance==nu.........
[1]php xml-rpc远程调用
来源: 互联网 发布时间: 2013-11-30
代码如下:
<?php
/*
从网上找来的XML-RPC库,对于开发小型的外部通讯接口很有用
*/
function & XML_serialize($data, $level = 0, $prior_key = NULL){
#assumes a hash, keys are the variable names
$xml_serialized_string = "";
while(list($key, $value) = each($data)){
$inline = false;
$numeric_array = false;
$attributes = "";
#echo "My current key is '$key', called with prior key '$prior_key'<br>";
if(!strstr($key, " attr")){ #if it's not an attribute
if(array_key_exists("$key attr", $data)){
while(list($attr_name, $attr_value) = each($data["$key attr"])){
#echo "Found attribute $attribute_name with value $attribute_value<br>";
$attr_value = &htmlspecialchars($attr_value, ENT_QUOTES);
$attributes .= " $attr_name=\"$attr_value\"";
}
}
if(is_numeric($key)){
#echo "My current key ($key) is numeric. My parent key is '$prior_key'<br>";
$key = $prior_key;
}else{
#you can't have numeric keys at two levels in a row, so this is ok
#echo "Checking to see if a numeric key exists in data.";
if(is_array($value) and array_key_exists(0, $value)){
# echo " It does! Calling myself as a result of a numeric array.<br>";
$numeric_array = true;
$xml_serialized_string .= XML_serialize($value, $level, $key);
}
#echo "<br>";
}
if(!$numeric_array){
$xml_serialized_string .= str_repeat("\t", $level) . "<$key$attributes>";
if(is_array($value)){
$xml_serialized_string .= "\r\n" . XML_serialize($value, $level+1);
}else{
$inline = true;
$xml_serialized_string .= htmlspecialchars($value);
}
$xml_serialized_string .= (!$inline ? str_repeat("\t", $level) : "") . "</$key>\r\n";
}
}else{
#echo "Skipping attribute record for key $key<bR>";
}
}
if($level == 0){
$xml_serialized_string = "<?xml version=\"1.0\" ?>\r\n" . $xml_serialized_string;
return $xml_serialized_string;
}else{
return $xml_serialized_string;
}
}
class XML {
var $parser; #a reference to the XML parser
var $document; #the entire XML structure built up so far
var $current; #a pointer to the current item - what is this
var $parent; #a pointer to the current parent - the parent will be an array
var $parents; #an array of the most recent parent at each level
var $last_opened_tag;
function XML($data=null){
$this->parser = xml_parser_create();
xml_parser_set_option ($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, "open", "close");
xml_set_character_data_handler($this->parser, "data");
# register_shutdown_function(array($this, 'destruct'));
}
function destruct(){
xml_parser_free($this->parser);
}
function parse($data){
$this->document = array();
$this->parent = $this->document;
$this->parents = array();
$this->last_opened_tag = NULL;
xml_parse($this->parser, $data);
return $this->document;
}
function open($parser, $tag, $attributes){
#echo "Opening tag $tag<br>\n";
$this->data = "";
$this->last_opened_tag = $tag; #tag is a string
if(array_key_exists($tag, $this->parent)){
#echo "There's already an instance of '$tag' at the current level ($level)<br>\n";
if(is_array($this->parent[$tag]) and array_key_exists(0, $this->parent[$tag])){ #if the keys are numeric
#need to make sure they're numeric (account for attributes)
$key = count_numeric_items($this->parent[$tag]);
#echo "There are $key instances: the keys are numeric.<br>\n";
}else{
#echo "There is only one instance. Shifting everything around<br>\n";
$temp = $this->parent[$tag];
unset($this->parent[$tag]);
$this->parent[$tag][0] = $temp;
if(array_key_exists("$tag attr", $this->parent)){
#shift the attributes around too if they exist
$temp = $this->parent["$tag attr"];
unset($this->parent["$tag attr"]);
$this->parent[$tag]["0 attr"] = $temp;
}
$key = 1;
}
$this->parent = $this->parent[$tag];
}else{
$key = $tag;
}
if($attributes){
$this->parent["$key attr"] = $attributes;
}
$this->parent[$key] = array();
$this->parent = $this->parent[$key];
array_unshift($this->parents, $this->parent);
}
function data($parser, $data){
#echo "Data is '", htmlspecialchars($data), "'<br>\n";
if($this->last_opened_tag != NULL){
$this->data .= $data;
}
}
function close($parser, $tag){
#echo "Close tag $tag<br>\n";
if($this->last_opened_tag == $tag){
$this->parent = $this->data;
$this->last_opened_tag = NULL;
}
array_shift($this->parents);
$this->parent = $this->parents[0];
}
}
function & XML_unserialize($xml){
$xml_parser = new XML();
$data = $xml_parser->parse($xml);
$xml_parser->destruct();
return $data;
}
function & XMLRPC_parse($request){
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_parse', "<p>Received the following raw request:</p>" . XMLRPC_show($request, 'print_r', true));
}
$data = &XML_unserialize($request);
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_parse', "<p>Returning the following parsed request:</p>" . XMLRPC_show($data, 'print_r', true));
}
return $data;
}
function & XMLRPC_prepare($data, $type = NULL){
if(is_array($data)){
$num_elements = count($data);
if((array_key_exists(0, $data) or !$num_elements) and $type != 'struct'){ #it's an array
if(!$num_elements){ #if the array is emptyempty
$returnvalue = array('array' => array('data' => NULL));
}else{
$returnvalue['array']['data']['value'] = array();
$temp = $returnvalue['array']['data']['value'];
$count = count_numeric_items($data);
for($n=0; $n<$count; $n++){
$type = NULL;
if(array_key_exists("$n type", $data)){
$type = $data["$n type"];
}
$temp[$n] = XMLRPC_prepare($data[$n], $type);
}
}
}else{ #it's a struct
if(!$num_elements){ #if the struct is emptyempty
$returnvalue = array('struct' => NULL);
}else{
$returnvalue['struct']['member'] = array();
$temp = $returnvalue['struct']['member'];
while(list($key, $value) = each($data)){
if(substr($key, -5) != ' type'){ #if it's not a type specifier
$type = NULL;
if(array_key_exists("$key type", $data)){
$type = $data["$key type"];
}
$temp[] = array('name' => $key, 'value' => XMLRPC_prepare($value, $type));
}
}
}
}
}else{ #it's a scalar
if(!$type){
if(is_int($data)){
$returnvalue['int'] = $data;
return $returnvalue;
}elseif(is_float($data)){
$returnvalue['double'] = $data;
return $returnvalue;
}elseif(is_bool($data)){
$returnvalue['boolean'] = ($data ? 1 : 0);
return $returnvalue;
}elseif(preg_match('/^\d{8}T\d{2}:\d{2}:\d{2}$/', $data, $matches)){ #it's a date
$returnvalue['dateTime.iso8601'] = $data;
return $returnvalue;
}elseif(is_string($data)){
$returnvalue['string'] = htmlspecialchars($data);
return $returnvalue;
}
}else{
$returnvalue[$type] = htmlspecialchars($data);
}
}
return $returnvalue;
}
function & XMLRPC_adjustValue($current_node){
if(is_array($current_node)){
if(isset($current_node['array'])){
if(!is_array($current_node['array']['data'])){
#If there are no elements, return an emptyempty array
return array();
}else{
#echo "Getting rid of array -> data -> value<br>\n";
$temp = $current_node['array']['data']['value'];
if(is_array($temp) and array_key_exists(0, $temp)){
$count = count($temp);
for($n=0;$n<$count;$n++){
$temp2[$n] = &XMLRPC_adjustValue($temp[$n]);
}
$temp = $temp2;
}else{
$temp2 = &XMLRPC_adjustValue($temp);
$temp = array($temp2);
#I do the temp assignment because it avoids copying,
# since I can put a reference in the array
#PHP's reference model is a bit silly, and I can't just say:
# $temp = array(&XMLRPC_adjustValue($temp));
}
}
}elseif(isset($current_node['struct'])){
if(!is_array($current_node['struct'])){
#If there are no members, return an emptyempty array
return array();
}else{
#echo "Getting rid of struct -> member<br>\n";
$temp = $current_node['struct']['member'];
if(is_array($temp) and array_key_exists(0, $temp)){
$count = count($temp);
for($n=0;$n<$count;$n++){
#echo "Passing name {$temp[$n][name]}. Value is: " . show($temp[$n][value], var_dump, true) . "<br>\n";
$temp2[$temp[$n]['name']] = &XMLRPC_adjustValue($temp[$n]['value']);
#echo "adjustValue(): After assigning, the value is " . show($temp2[$temp[$n]['name']], var_dump, true) . "<br>\n";
}
}else{
#echo "Passing name $temp[name]<br>\n";
$temp2[$temp['name']] = &XMLRPC_adjustValue($temp['value']);
}
$temp = $temp2;
}
}else{
$types = array('string', 'int', 'i4', 'double', 'dateTime.iso8601', 'base64', 'boolean');
$fell_through = true;
foreach($types as $type){
if(array_key_exists($type, $current_node)){
#echo "Getting rid of '$type'<br>\n";
$temp = $current_node[$type];
#echo "adjustValue(): The current node is set with a type of $type<br>\n";
$fell_through = false;
break;
}
}
if($fell_through){
$type = 'string';
#echo "Fell through! Type is $type<br>\n";
}
switch ($type){
case 'int': case 'i4': $temp = (int)$temp; break;
case 'string': $temp = (string)$temp; break;
case 'double': $temp = (double)$temp; break;
case 'boolean': $temp = (bool)$temp; break;
}
}
}else{
$temp = (string)$current_node;
}
return $temp;
}
function XMLRPC_getParams($request){
if(!is_array($request['methodCall']['params'])){
#If there are no parameters, return an emptyempty array
return array();
}else{
#echo "Getting rid of methodCall -> params -> param<br>\n";
$temp = $request['methodCall']['params']['param'];
if(is_array($temp) and array_key_exists(0, $temp)){
$count = count($temp);
for($n = 0; $n < $count; $n++){
#echo "Serializing parameter $n<br>";
$temp2[$n] = &XMLRPC_adjustValue($temp[$n]['value']);
}
}else{
$temp2[0] = &XMLRPC_adjustValue($temp['value']);
}
$temp = $temp2;
return $temp;
}
}
function XMLRPC_getMethodName($methodCall){
#returns the method name
return $methodCall['methodCall']['methodName'];
}
function XMLRPC_request($site, $location, $methodName, $params = NULL, $user_agent = NULL){
$site = explode(':', $site);
if(isset($site[1]) and is_numeric($site[1])){
$port = $site[1];
}else{
$port = 80;
}
$site = $site[0];
$data["methodCall"]["methodName"] = $methodName;
$param_count = count($params);
if(!$param_count){
$data["methodCall"]["params"] = NULL;
}else{
for($n = 0; $n<$param_count; $n++){
$data["methodCall"]["params"]["param"][$n]["value"] = $params[$n];
}
}
$data = XML_serialize($data);
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_request', "<p>Received the following parameter list to send:</p>" . XMLRPC_show($params, 'print_r', true));
}
$conn = fsockopen ($site, $port); #open the connection
if(!$conn){ #if the connection was not opened successfully
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_request', "<p>Connection failed: Couldn't make the connection to $site.</p>");
}
return array(false, array('faultCode'=>10532, 'faultString'=>"Connection failed: Couldn't make the connection to $site."));
}else{
$headers =
"POST $location HTTP/1.0\r\n" .
"Host: $site\r\n" .
"Connection: close\r\n" .
($user_agent ? "User-Agent: $user_agent\r\n" : '') .
"Content-Type: text/xml\r\n" .
"Content-Length: " . strlen($data) . "\r\n\r\n";
fputs($conn, "$headers");
fputs($conn, $data);
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_request', "<p>Sent the following request:</p>\n\n" . XMLRPC_show($headers . $data, 'print_r', true));
}
#socket_set_blocking ($conn, false);
$response = "";
while(!feof($conn)){
$response .= fgets($conn, 1024);
}
fclose($conn);
#strip headers off of response
$data = XML_unserialize(substr($response, strpos($response, "\r\n\r\n")+4));
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_request', "<p>Received the following response:</p>\n\n" . XMLRPC_show($response, 'print_r', true) . "<p>Which was serialized into the following data:</p>\n\n" . XMLRPC_show($data, 'print_r', true));
}
if(isset($data['methodResponse']['fault'])){
$return = array(false, XMLRPC_adjustValue($data['methodResponse']['fault']['value']));
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_request', "<p>Returning:</p>\n\n" . XMLRPC_show($return, 'var_dump', true));
}
return $return;
}else{
$return = array(true, XMLRPC_adjustValue($data['methodResponse']['params']['param']['value']));
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_request', "<p>Returning:</p>\n\n" . XMLRPC_show($return, 'var_dump', true));
}
return $return;
}
}
}
function XMLRPC_response($return_value, $server = NULL){
$data["methodResponse"]["params"]["param"]["value"] = $return_value;
$return = XML_serialize($data);
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_response', "<p>Received the following data to return:</p>\n\n" . XMLRPC_show($return_value, 'print_r', true));
}
header("Connection: close");
header("Content-Length: " . strlen($return));
header("Content-Type: text/xml");
header("Date: " . date("r"));
if($server){
header("Server: $server");
}
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_response', "<p>Sent the following response:</p>\n\n" . XMLRPC_show($return, 'print_r', true));
}
echo $return;
}
function XMLRPC_error($faultCode, $faultString, $server = NULL){
$array["methodResponse"]["fault"]["value"]["struct"]["member"] = array();
$temp = $array["methodResponse"]["fault"]["value"]["struct"]["member"];
$temp[0]["name"] = "faultCode";
$temp[0]["value"]["int"] = $faultCode;
$temp[1]["name"] = "faultString";
$temp[1]["value"]["string"] = $faultString;
$return = XML_serialize($array);
header("Connection: close");
header("Content-Length: " . strlen($return));
header("Content-Type: text/xml");
header("Date: " . date("r"));
if($server){
header("Server: $server");
}
if(defined('XMLRPC_DEBUG') and XMLRPC_DEBUG){
XMLRPC_debug('XMLRPC_error', "<p>Sent the following error response:</p>\n\n" . XMLRPC_show($return, 'print_r', true));
}
echo $return;
}
function XMLRPC_convert_timestamp_to_iso8601($timestamp){
#takes a unix timestamp and converts it to iso8601 required by XMLRPC
#an example iso8601 datetime is "20010822T03:14:33"
return date("Ymd\TH:i:s", $timestamp);
}
function XMLRPC_convert_iso8601_to_timestamp($iso8601){
return strtotime($iso8601);
}
function count_numeric_items($array){
return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;
}
function XMLRPC_debug($function_name, $debug_message){
$GLOBALS['XMLRPC_DEBUG_INFO'][] = array($function_name, $debug_message);
}
function XMLRPC_debug_print(){
if($GLOBALS['XMLRPC_DEBUG_INFO']){
echo "<table border=\"1\" width=\"100%\">\n";
foreach($GLOBALS['XMLRPC_DEBUG_INFO'] as $debug){
echo "<tr><th vertical-align: top\">$debug[0]</th><td>$debug[1]</td></tr>\n";
}
echo "</table>\n";
unset($GLOBALS['XMLRPC_DEBUG_INFO']);
}else{
echo "<p>No debugging information available yet.</p>";
}
}
function XMLRPC_show($data, $func = "print_r", $return_str = false){
ob_start();
$func($data);
$output = ob_get_contents();
ob_end_clean();
if($return_str){
return "<pre>" . htmlspecialchars($output) . "</pre>\n";
}else{
echo "<pre>", htmlspecialchars($output), "</pre>\n";
}
}
?>
服务端程序例子,server.php
代码如下:
<?
include 'xml-rpc.inc.php';
//定义可被远程调用的方法
$xmlrpc_methods=array();
$xmlrpc_methods['insertRecords']='insertRecords';
//获得用户传入的方法名和参数
$xmlrpc_request = XMLRPC_parse($HTTP_RAW_POST_DATA);
$methodName = XMLRPC_getMethodName($xmlrpc_request);
$params = XMLRPC_getParams($xmlrpc_request);
if (!isset($xmlrpc_methods[$methodName])){
XMLRPC_error('1',"你所调用的方法不存在");
}else {
$xmlrpc_methods[$methodName]($params);
}
function insertRecords($params){
if (emptyempty($params)){
XMLRPC_error('2',"参数出错");
}
XMLRPC_response(XMLRPC_prepare('http://www.emtit.com'));
}
?>
PHP客户端调用服务端方法例子
代码如下:
<?php
include_once 'xml-rpc.inc';
$params=array(2,3);
$result=XMLRPC_request("127.0.0.1","/services/server.php","insertRecords",$params);//服务端文件放在services文件夹下
print_r($result);
?>
结果会显示www.emtiit.com
[2]php 设计模式之 工厂模式
来源: 互联网 发布时间: 2013-11-30
本人常用mysql数据库,所以程序只写了mysql的数据库操作类。希望各位高手把另外的类写全,最好能发一份给我。
db_mysql.php继承db.php接口,具体实现数据库操作的各种方法 ,如果你确定你的数据库平台不会变的话不用工厂类,直接用这个就行了。
<?php
/**
* @author 黄建文
* @version V1.0
* @email hjwtp2005@qq.com
* @data 2008-12-16
* ==================================================================
* @example
* include 'db_mysql.php';
* $db=new db_mysql('localhost','root','admin','emtit');
* $sqlstr="SELECT * FROM member WHERE memberid=1";
* var_dump($db->get_one($sqlstr));
* ===================================================================
*/
include 'db.php';
class db_mysql implements db {
private $connid;
public function db_mysql($dbhost,$username,$passowrd,$dbname='',$dbcharset='utf8'){
$this->connid=mysql_connect($dbhost,$username,$passowrd);
if (!$this->connid){
$this->halt('Can not connect to MySQL server');
}
if (emptyempty($dbcharset)){
$dbcharset='utf8';
}
// 当mysql版本为4.1以上时,启用数据库字符集设置
if($this->version() > '4.1' && $dbcharset)
{
mysql_query("SET NAMES '".$dbcharset."'" , $this->connid);
}
// 当mysql版本为5.0以上时,设置sql mode
if($this->version() > '5.0')
{
mysql_query("SET sql_mode=''" , $this->connid);
}
if (!emptyempty($dbname)){
$this->select_db($dbname);
}
}
/**
* 选择数据库
*
* @param unknown_type $dbname
*/
public function select_db($dbname){
mysql_select_db($dbname,$this->connid);
}
/**
* 执行SQL语句
*
* @param unknown_type $sqlstr
*/
public function query($sqlstr){
$query=mysql_query($sqlstr,$this->connid);
if (!$query){
$this->halt('MySQL Query Error', $sqlstr);
}
return $query;
}
/**
* 取得一条查询记录
*
* @return unknown
*/
public function get_one($sqlstr){
$query=$this->query($sqlstr);
$rs = $this->fetch_array($query);
$this->free_result($query);
return $rs ;
}
/**
* 从结果集中取得一行作为关联数组
* @param resource 数据库查询结果资源
* @param string 定义返回类型
* @return array
*/
public function fetch_array($query, $result_type = MYSQL_ASSOC)
{
return mysql_fetch_array($query, $result_type);
}
/**
* 取得前一次 MySQL 操作所影响的记录行数
* @return int
*/
public function affected_rows()
{
return mysql_affected_rows($this->connid);
}
/**
* 取得结果集中行的数目
* @return int
*/
public function num_rows($query)
{
return mysql_num_rows($query);
}
/**
* 返回结果集中字段的数目
* @return int
*/
public function num_fields($query)
{
return mysql_num_fields($query);
}
/**
* 释放结果内存
*
* @param unknown_type $query
* @return bool
*/
public function free_result($query)
{
return mysql_free_result($query);
}
/**
* 取得上一步 INSERT 操作产生的 ID
* @return int
*/
public function insert_id()
{
return mysql_insert_id($this->connid);
}
/**
* 取得 MySQL 服务器信息
*
* @return string
*/
public function version()
{
return mysql_get_server_info($this->connid);
}
/**
* 关闭MYSQL连接
*
* @return bool
*/
public function close()
{
return mysql_close($this->connid);
}
/**
* 返回错误字符串
*
* @return string
*/ private function error(){
return @mysql_error($this->connid);
}
/**
* 返回错误号
*
* @return int
*/
private function errno(){
return intval(@mysql_errno($this->connid)) ;
}
/**
* 输出出错信息
*
* @param string $message
* @param string $sql
*/
private function halt($message = '', $sql = ''){
exit("MySQL Query:$sql <br> MySQL Error:".$this->error()." <br> MySQL Errno:".$this->errno()." <br> Message:$message");
}
}
?>
db.php数据库操作接口,定义数据库操作的方法.
<?php
interface db {
function select_db($dbname);//选择数据库
function query($sqlstr);//执行sql语句
function get_one($sqlstr);//执行sql语句,只得到一条记录
function fetch_array($query);//从结果集中取得一行作为关联数组
function affected_rows();//返回操作所影响的记录行数
function num_rows($query);//取得结果集中行的数目
function num_fields($query);//返回结果集中字段的数目
function free_result($query);//释放资源
function insert_id();//返回上一次插入记录的ID;
function version();//数据库版本
function close();//关闭数据库连接
}
?>
db_factory.php数据库工厂类,要实现数据库平台更方便一定要使用这个类
<?php
/**
* @author 黄建文
* @version v1.0
* @email hjwtp2005@qq.com
* @example
* $db=db_factcory::create('MYSQL','localhost','root','admin','emtit');
* $sqlstr="SELECT * FROM member WHERE memberid=1";
* $db->get_one($sqlstr);
*/
include 'db_mysql.php';
class db_factory {
function db_factory() {
}
static function create($type,$dbhost,$username,$password,$dbname='',$dbcharset=''){
switch ($type){
case 'MYSQL':
return new db_mysql($dbhost,$username,$password,$dbname,$dbcharset);
case 'SQLSERVER':
return new db_sqlserver($dbhost,$username,$password,$dbname,$dbcharset);
case 'ACCESS':
return new db_access($dbhost,$username,$password,$dbname,$dbcharset);
case 'ORACLE':
return new db_oracle($dbhost,$username,$password,$dbname,$dbcharset);
}
return false;
}
function __destruct() {
}
}
?>
db_mysql.php继承db.php接口,具体实现数据库操作的各种方法 ,如果你确定你的数据库平台不会变的话不用工厂类,直接用这个就行了。
代码如下:
<?php
/**
* @author 黄建文
* @version V1.0
* @email hjwtp2005@qq.com
* @data 2008-12-16
* ==================================================================
* @example
* include 'db_mysql.php';
* $db=new db_mysql('localhost','root','admin','emtit');
* $sqlstr="SELECT * FROM member WHERE memberid=1";
* var_dump($db->get_one($sqlstr));
* ===================================================================
*/
include 'db.php';
class db_mysql implements db {
private $connid;
public function db_mysql($dbhost,$username,$passowrd,$dbname='',$dbcharset='utf8'){
$this->connid=mysql_connect($dbhost,$username,$passowrd);
if (!$this->connid){
$this->halt('Can not connect to MySQL server');
}
if (emptyempty($dbcharset)){
$dbcharset='utf8';
}
// 当mysql版本为4.1以上时,启用数据库字符集设置
if($this->version() > '4.1' && $dbcharset)
{
mysql_query("SET NAMES '".$dbcharset."'" , $this->connid);
}
// 当mysql版本为5.0以上时,设置sql mode
if($this->version() > '5.0')
{
mysql_query("SET sql_mode=''" , $this->connid);
}
if (!emptyempty($dbname)){
$this->select_db($dbname);
}
}
/**
* 选择数据库
*
* @param unknown_type $dbname
*/
public function select_db($dbname){
mysql_select_db($dbname,$this->connid);
}
/**
* 执行SQL语句
*
* @param unknown_type $sqlstr
*/
public function query($sqlstr){
$query=mysql_query($sqlstr,$this->connid);
if (!$query){
$this->halt('MySQL Query Error', $sqlstr);
}
return $query;
}
/**
* 取得一条查询记录
*
* @return unknown
*/
public function get_one($sqlstr){
$query=$this->query($sqlstr);
$rs = $this->fetch_array($query);
$this->free_result($query);
return $rs ;
}
/**
* 从结果集中取得一行作为关联数组
* @param resource 数据库查询结果资源
* @param string 定义返回类型
* @return array
*/
public function fetch_array($query, $result_type = MYSQL_ASSOC)
{
return mysql_fetch_array($query, $result_type);
}
/**
* 取得前一次 MySQL 操作所影响的记录行数
* @return int
*/
public function affected_rows()
{
return mysql_affected_rows($this->connid);
}
/**
* 取得结果集中行的数目
* @return int
*/
public function num_rows($query)
{
return mysql_num_rows($query);
}
/**
* 返回结果集中字段的数目
* @return int
*/
public function num_fields($query)
{
return mysql_num_fields($query);
}
/**
* 释放结果内存
*
* @param unknown_type $query
* @return bool
*/
public function free_result($query)
{
return mysql_free_result($query);
}
/**
* 取得上一步 INSERT 操作产生的 ID
* @return int
*/
public function insert_id()
{
return mysql_insert_id($this->connid);
}
/**
* 取得 MySQL 服务器信息
*
* @return string
*/
public function version()
{
return mysql_get_server_info($this->connid);
}
/**
* 关闭MYSQL连接
*
* @return bool
*/
public function close()
{
return mysql_close($this->connid);
}
/**
* 返回错误字符串
*
* @return string
*/ private function error(){
return @mysql_error($this->connid);
}
/**
* 返回错误号
*
* @return int
*/
private function errno(){
return intval(@mysql_errno($this->connid)) ;
}
/**
* 输出出错信息
*
* @param string $message
* @param string $sql
*/
private function halt($message = '', $sql = ''){
exit("MySQL Query:$sql <br> MySQL Error:".$this->error()." <br> MySQL Errno:".$this->errno()." <br> Message:$message");
}
}
?>
db.php数据库操作接口,定义数据库操作的方法.
代码如下:
<?php
interface db {
function select_db($dbname);//选择数据库
function query($sqlstr);//执行sql语句
function get_one($sqlstr);//执行sql语句,只得到一条记录
function fetch_array($query);//从结果集中取得一行作为关联数组
function affected_rows();//返回操作所影响的记录行数
function num_rows($query);//取得结果集中行的数目
function num_fields($query);//返回结果集中字段的数目
function free_result($query);//释放资源
function insert_id();//返回上一次插入记录的ID;
function version();//数据库版本
function close();//关闭数据库连接
}
?>
db_factory.php数据库工厂类,要实现数据库平台更方便一定要使用这个类
代码如下:
<?php
/**
* @author 黄建文
* @version v1.0
* @email hjwtp2005@qq.com
* @example
* $db=db_factcory::create('MYSQL','localhost','root','admin','emtit');
* $sqlstr="SELECT * FROM member WHERE memberid=1";
* $db->get_one($sqlstr);
*/
include 'db_mysql.php';
class db_factory {
function db_factory() {
}
static function create($type,$dbhost,$username,$password,$dbname='',$dbcharset=''){
switch ($type){
case 'MYSQL':
return new db_mysql($dbhost,$username,$password,$dbname,$dbcharset);
case 'SQLSERVER':
return new db_sqlserver($dbhost,$username,$password,$dbname,$dbcharset);
case 'ACCESS':
return new db_access($dbhost,$username,$password,$dbname,$dbcharset);
case 'ORACLE':
return new db_oracle($dbhost,$username,$password,$dbname,$dbcharset);
}
return false;
}
function __destruct() {
}
}
?>
[3]php 设计模式之 单例模式
来源: 互联网 发布时间: 2013-11-30
小船类boat.php
<?php
class boat {
private static $instance=null;
private $skipper;
private $personNum=0;
private $passengers=array();
private function __construct() {
}
public static function getInstance(){
if (self::$instance==null){
self::$instance=new boat();
}
return self::$instance;
}
/**
* 设置船长
*
* @param unknown_type $name
*/
public function setSkipper($name){
$this->skipper=$name;
}
/**
* 装人
*
* @param unknown_type $person
*/
public function load($person){
if (!emptyempty($person) and $this->personNum<=5){
array_push($this->passengers,$person);
$this->personNum=$this->personNum+1;
}
if ($this->personNum>5) {
echo 'this boat only load 5 person!';
}
}
/**
* 船上装了什么人
*
* @return unknown
*/
public function whoInBoat(){
return $this->passengers;
}
}
?>
现在看看怎么样上客
<?php
include 'boat.php';
echo "从前有一条河,河里只有一条船,<br>";
$boat1=boat::getInstance();//因为只有一条船,所以只有一个实例
echo "现在张三要到河东去,";
$boat1->load('张三');
echo "<br>现在船上坐着:<br>";
foreach ($boat1->whoInboat() as $who){
echo $who.'<br>';
}
echo "<br>现在李四也要过河东去<br>";
$boat1->load('李四');
echo "现在船上坐着:<br>";
foreach ($boat1->whoInboat() as $who){
echo $who.'、';
}
echo "<br><br>王五以为这条河有另一条船,<br>";
$boat2=boat::getInstance();
echo "他现在上船<br>";
$boat2->load('王五');
echo "现在船上坐着:<br>";
foreach ($boat1->whoInboat() as $who){
echo $who.'、';
}
?>
代码如下:
<?php
class boat {
private static $instance=null;
private $skipper;
private $personNum=0;
private $passengers=array();
private function __construct() {
}
public static function getInstance(){
if (self::$instance==null){
self::$instance=new boat();
}
return self::$instance;
}
/**
* 设置船长
*
* @param unknown_type $name
*/
public function setSkipper($name){
$this->skipper=$name;
}
/**
* 装人
*
* @param unknown_type $person
*/
public function load($person){
if (!emptyempty($person) and $this->personNum<=5){
array_push($this->passengers,$person);
$this->personNum=$this->personNum+1;
}
if ($this->personNum>5) {
echo 'this boat only load 5 person!';
}
}
/**
* 船上装了什么人
*
* @return unknown
*/
public function whoInBoat(){
return $this->passengers;
}
}
?>
现在看看怎么样上客
代码如下:
<?php
include 'boat.php';
echo "从前有一条河,河里只有一条船,<br>";
$boat1=boat::getInstance();//因为只有一条船,所以只有一个实例
echo "现在张三要到河东去,";
$boat1->load('张三');
echo "<br>现在船上坐着:<br>";
foreach ($boat1->whoInboat() as $who){
echo $who.'<br>';
}
echo "<br>现在李四也要过河东去<br>";
$boat1->load('李四');
echo "现在船上坐着:<br>";
foreach ($boat1->whoInboat() as $who){
echo $who.'、';
}
echo "<br><br>王五以为这条河有另一条船,<br>";
$boat2=boat::getInstance();
echo "他现在上船<br>";
$boat2->load('王五');
echo "现在船上坐着:<br>";
foreach ($boat1->whoInboat() as $who){
echo $who.'、';
}
?>
最新技术文章: