PHP中名字空间和类的自动加载
编辑时间:2017-03-26 作者:金满斗 浏览量:1989 来源:原创

说实话,我的技术除了家电维修技术以外,别的基本都是自学的,想当年学习php的时候,那时候教程都是以5.2版本讲的,5.3似乎刚刚发行。而我又不是专业的php程序员,也就听个晕晕乎乎吧,自己也为自己做过简单的网页,但还是实现目的为主。后来有幸参加php类的工作,上手就直接是thinkphp了,thinkphp为我们小白简化了太多的东西。

前几天自己一个软件上需要一个配套的网页,这么简单的东西不可能用thinkphp,自己就简单的写了个,也算是对基础的一个再学习巩固吧。php就这点不好,软件不段升级,函数也更新迭代很快,然人不知道以后用什么函数最合适。虽然引进了名字空间的概念,但我觉得函数还没有分门别类,感觉很杂乱,这点就不如aardio了。当然,这也和php是多人维护的有一些关系吧。


废话少说了,直接讲过程吧。简单网页,目录构造截图,classes里面肯定就是放的类啦,config文件夹里放的配置文件 init.db,php  初始引用init.php

111.jpg

先init.db.php  ,是不是有点thinkphp配置文件的感觉,哈哈,本来就是一样的,人家的长处还是要吸取的。

<?php	return array(
	'DB_HOST' => 'localhost',
	'DB_NAME'    => '数据库名',
	'DB_USER' => '数据库用户名',
	'DB_PWD' => '密码',
	'DB_PORT' => 3306,
	'DB_PREFIX' => 'cy_',
	'DB_CHARSET' => 'utf8'
	);

再初始引用文件

init.php

<?php

$config = require_once 'init.db.php';//var_dump($config);//类的自动加载,新建什么类就自动加载什么类function my_autoloader($class) {
	//echo $class . '.class.php<br/>';
	include  $class . '.class.php';}spl_autoload_register('my_autoloader');use classes\JinMysql;   //载入扩展数据库$db  = new JinMysql($config["DB_HOST"],$config["DB_USER"],$config["DB_PWD"],$config["DB_NAME"]);?>

自己写的个扩展数据库,估计增加那个也许错了,没测试,改进的余地太大,那天晚上熬夜写的,如果数据表是用的我以前写的老表,当时没有前缀,这里也就把前缀去了,其实以后用的话还是要根据实际修改的

JinMysql.class.php

<?php /*自己封装的数据库函数库*/namespace classes;use MySQLi;     //把mysli引入名字空间class JinMysql extends  MySQLi{
	private $per = "";     //表格前缀
		//类的构造函数
	 public function __construct($host, $user, $pass, $db) {
	        parent::init();     //parent 调用父类
	
	        if (!parent::options(MYSQLI_INIT_COMMAND, 'set names utf8')) {   //设置编码
	            die('Setting MYSQLI_INIT_COMMAND failed');
	        }
	
	        if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
	            die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
	        }
	
	        if (!parent::real_connect($host, $user, $pass, $db)) {
	            die('Connect Error (' . mysqli_connect_errno() . ') '
	                    . mysqli_connect_error());
	        } 
	        
	    }
	    
	 /* 取数组,返回数组 */    
	 public function  getTab($sql){
	 	$result = parent::query($sql) or("操作dql失败".$this->error);
	 	if($this->field_count){     /*返回对象列数,用于判断是否有值*/
	 	$data = array();
	 	while ($row = $result->fetch_row()) {
	 		$data[]= $row ; 
	    }
	    /* 释放资源 */
	    $result->close();
	    return $data;
	 	}
	 }
	 
    
	 
	 //查询
	 /*
	  * query 查询返回多条
	  * field 字段
	  * tablename 表名
	  * perpage 每页显示
	  * selpage 当前页
	  * where 条件
	  * orderby 排序
	  */
	  public function getTable($tableName, $field = null, $perpage = null, $selpage = 1, $where = null, $orderby=null){
	 	if(!$tableName) return false;
	 	$field = $field ? $field : '*';
	 	$perpage = $perpage ? (int)$perpage : false;
	 	$selpage = $selpage ? (int)$selpage : false;
	 	$where = $where ? $where : false;
	 	$orderby = $orderby ? $orderby : false;
	 
	 	$sql = "SELECT $field  FROM  $tableName  ";
	 	if($where) $sql = $sql. 'WHERE '. $where. ' ';
	 	if($orderby) $sql = "$sql ORDER BY $orderby ";
	 	if($perpage and $selpage) $sql = $sql. 'limit ' .($selpage-1)*$perpage .',' .$perpage;
	 	$result = $this -> getTab($sql);
	 	return $result;
	 }
	 
	 
 
	 
	 
    

	 /* 添加数据到数据库
	  * insert 插入数据
	  * tableName 表格名
	  * fieldTable table 字段名=》值
	  */
	 public function insert($tableName, $fieldTable){
	 	$fieldVar = '';
	 	$fieldVal = '';
	 	foreach ($fieldTable as $k =>$v ){
	 		$fieldVar = $fieldVar . $k . ',';
	 		$fieldVal = $fieldVal . '@' . $k . ',';
	 	}
	 	//清除最后一个逗号
	 	$fieldVar = rtrim( trim($fieldVar), ',' );
	 	$fieldVal = rtrim( trim($fieldVal), ',' );
	 	//拼接sql语句
	 	$sql = "INSERT INTO [$tableName ]($fieldVar ) VALUES($fieldVal )";
	 	//执行SQL语句
	 	return parent::query($sql, $fieldTable);
	 }
	 
	 
	 //查询总数
	 /*
	  * getCount 查询数量
	  * tableName 表名
	  * where 条件语句
	  */
	 public function getCount($tableName, $where=null){
	 	if(empty($tableName)) return false;
	 	$where = $where ? $where : false;
	 	$sql = "SELECT COUNT(*) FROM  $tableName ";
	 	if($where) $sql = "$sql WHERE  $where ";
	 	$result = $this -> getTab($sql);
	 	return  $result[0][0];
	 }    
   
    }

	?>

还有一个分页库,这里是用的别人现成的,这里一起贴出来算了  Page.class.php

<?php/*省的改模版,对这个分页按模版样式进行修改    20160420 邓继松*/namespace classes;class Page {
	private $total; //数据表中总记录数
	private $listRows; //每页显示行数
	private $limit;
	private $uri;
	private $pageNum; //页数
	private $config=array('header'=>"个记录", "prev"=>"上一页", "next"=>"下一页", "first"=>"首 页", "last"=>"尾 页");
	private $listNum=8;
	/*
	 * $total
	 * $listRows
	 */
	public function __construct($total, $listRows=10, $pa=""){
		$this->total=$total;
		$this->listRows=$listRows;
		$this->uri=$this->getUri($pa);
		$this->page=!empty($_GET["page"]) ? $_GET["page"] : 1;
		$this->pageNum=ceil($this->total/$this->listRows);
		$this->limit=$this->setLimit();
	}

	private function setLimit(){
		return "Limit ".($this->page-1)*$this->listRows.", {$this->listRows}";
	}

	private function getUri($pa){
		$url=$_SERVER["REQUEST_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?").$pa;
		$parse=parse_url($url);

		if(isset($parse["query"])){
			parse_str($parse['query'],$params);
			unset($params["page"]);
			$url=$parse['path'].'?'.http_build_query($params);

		}

		return $url;
	}

	function __get($args){
		if($args=="limit")
			return $this->limit;
		else
			return null;
	}

	private function start(){
		if($this->total==0)
			return 0;
		else
			return ($this->page-1)*$this->listRows+1;
	}

	private function end(){
		return min($this->page*$this->listRows,$this->total);
	}

	private function first(){
		$html = "";
		if($this->page==1)
			$html.='';
		else
			$html.="&nbsp;&nbsp;<a href='{$this->uri}&page=1'>{$this->config["first"]}</a>&nbsp;&nbsp;";

		return $html;
	}

	private function prev(){
		$html = "";
		if($this->page==1)
			$html.='';
		else
			$html.="&nbsp;&nbsp;<a href='{$this->uri}&page=".($this->page-1)."'>{$this->config["prev"]}</a>&nbsp;&nbsp;";

		return $html;
	}

	private function pageList(){
		$linkPage="";
			
		$inum=floor($this->listNum/2);

		for($i=$inum; $i>=1; $i--){
			$page=$this->page-$i;

			if($page<1)
				continue;

			$linkPage.="&nbsp;<a href='{$this->uri}&page={$page}'>{$page}</a>&nbsp;";

		}

		$linkPage.="&nbsp;{$this->page}&nbsp;";
			

		for($i=1; $i<=$inum; $i++){
			$page=$this->page+$i;
			if($page<=$this->pageNum)
				$linkPage.="&nbsp;<a href='{$this->uri}&page={$page}'>{$page}</a>&nbsp;";
			else
				break;
		}

		return $linkPage;
	}

	private function next(){
		$html = "";
		if($this->page==$this->pageNum)
			$html.='';
		else
			$html.="&nbsp;&nbsp;<a href='{$this->uri}&page=".($this->page+1)."'>{$this->config["next"]}</a>&nbsp;&nbsp;";

		return $html;
	}

	private function last(){
		$html = "";
		if($this->page==$this->pageNum)
			$html.='';
		else
			$html.="&nbsp;&nbsp;<a href='{$this->uri}&page=".($this->pageNum)."'>{$this->config["last"]}</a>&nbsp;&nbsp;";

		return $html;
	}

	private function goPage(){
		return '&nbsp;&nbsp;<input type="text" onkeydown="javascript:if(event.keyCode==13){var page=(this.value>'.$this->pageNum.')?'.$this->pageNum.':this.value;location=\''.$this->uri.'&page=\'+page+\'\'}" value="'.$this->page.'" style="width:25px"><input type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value>'.$this->pageNum.')?'.$this->pageNum.':this.previousSibling.value;location=\''.$this->uri.'&page=\'+page+\'\'">&nbsp;&nbsp;';
	}
	function fpage($display=array(0,1,2,3,4,5,6,7,8)){
		$html[0]="&nbsp;&nbsp;共有<b>{$this->total}</b>{$this->config["header"]}&nbsp;&nbsp;";
		$html[1]="&nbsp;&nbsp;每页显示<b>".($this->end()-$this->start()+1)."</b>条,本页<b>{$this->start()}-{$this->end()}</b>条&nbsp;&nbsp;";
		$html[2]="&nbsp;&nbsp;<b>{$this->page}/{$this->pageNum}</b>页&nbsp;&nbsp;";
		$html[3]=$this->first();
		$html[4]=$this->prev();
		$html[5]=$this->pageList();
		$html[6]=$this->next();
		$html[7]=$this->last();
		$html[8]=$this->goPage();
		$fpage='';
		foreach($display as $index){
		$fpage.=$html[$index];
		}

		return $fpage;

	}

	}

最后最终页面调用的例子,没用模版,小网页省的复杂了

<?php 
header("Content-type;text/html;charset=utf-8");require_once 'config/init.php';use classes\Page;       //载入分页库$selpage = empty($_GET['page'])? 1 :(int)$_GET['page'] ;$count = $db -> getCount("cyruanj");$perpage = 8;$page = new Page($count,$perpage);   // 实例化分页类 传入总记录数和每页显示的记录数$pagehtml = $page->fpage(array(1,2,3,4,5,6,7)); // 分页显示输出$data = $db->gettable('cyruanj',null,$perpage,$selpage,null," id desc");   //取出数组到网页里直接调用就行  $db->close();?>


来说两句吧