>  기사  >  php教程  >  데이터베이스 작업을 위한 모델 클래스는 __call 메서드를 사용합니다.

데이터베이스 작업을 위한 모델 클래스는 __call 메서드를 사용합니다.

WBOY
WBOY원래의
2016-08-22 10:13:311358검색
다음으로 이동 [1] [2] [전체 화면 미리보기]
<?
	/*
		作者 : shyhero
		邮箱 : shyhero@outlook.com
		Q  Q : 1757424878
	 */
	define("HOSTNAME","127.0.0.1");
	define("USERNAME","root");
	define("PASSWORD","");
	define("DATANAME","class");

	class Model{
		private $link;
		private $tableName;
		private $zd;
		private $method = array(
			"where" => "",
			"order" => "",
			"limit" => "",
			"group" => "",
			"having" => ""
			);
		public function __construct($tableName){
			$this -> tableName = $tableName;
			try{
				$this -> link = mysqli_connect(HOSTNAME,USERNAME,PASSWORD,DATANAME);
				mysqli_set_charset($this -> link,"UTF8");
			}catch(Exception $e){
				echo "数据库连接失败";
			}
			$this -> desc();
		}
		public function __destruct(){
			mysqli_close($this -> link);
		}
		public function desc(){
			$sql = " desc {$this -> tableName}; ";
			$res = mysqli_query($this -> link,$sql);
			$arr = mysqli_fetch_all($res,MYSQLI_ASSOC);
			for($i = 0 ;$i < count($arr);$i++){
				$brr[] = $arr[$i]['Field'];
			}
			$this -> zd = $brr;
			return $brr;
		}
		public function __call($name,$value){
			$name = strtolower($name);
			if(array_key_exists($name,$this -> method)){
				if($name == 'order'){
					$this -> method['order']  = " order by ".$value[0];
				}elseif($name == 'group'){
				$this -> method['group']  = " group by ".$value[0];
				}else{
					$this -> method[$name]  = " {$name} ".$value[0];
				}
			}else{
				return "the method is not found!";
			}
			return $this;
		}
		public function method(){
			return " {$this -> method['where']} {$this -> method['order']} {$this -> method['limit']} {$this -> method['group']} {$this -> method['having']}; ";
		}
		public function find($a="*"){
			if(in_array("{$a}",$this -> zd) || $a == "*"){
				$sql = "select {$a} from {$this -> tableName} {$this -> method()} ";
			}else{
				$sql = "select * from {$this -> tableName}";
			}
			//return $sql;
			$res = mysqli_query($this -> link,$sql);
			$arr = mysqli_fetch_all($res,MYSQLI_ASSOC);
			return $arr;
		}
	}

2. [코드][PHP]코드 다음으로 이동 [1] [2] [전체 화면 미리보기]

<?
	function __autoload($className){
		require($className.".class.php");
	}

	$a = new Model("stu");
	$a -> where("name = 'zhu'")->limit("5,10");
	var_dump($a -> find("name"));
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.