热搜:NVER node 开发 php

如何用PHP写一个框架

2024-07-28 14:40:01
如何用PHP写一个框架

大三学生一枚,第一次写框架,仿照着THINKPHP 3.2.3,写的不好请多多包涵

树形图如图所示

kakoi 文件夹存放着核心配置文件

Home 文件夹中包含着控制层Controller

数据层Model

以及模板层View和缓存Cache

PUBLIC 主要存储 JS/css/等

框架是基于单入口文件 index.php

此处可以实现分组操作。

<?php//入口文件		//项目文件名称				//DEFINE('OTHER','Admin');		//配置其他文件夹		//配置文件夹请直接写入文件夹名称即可		$OTHER = 'Admin';		DEFINE('EVENT','./Event');		// 引入核心配置文件		require "kakoi/kakoi.php";		?>

引入核心配置

<?phpheader("Content-type: text/html; charset=utf-8"); spl_autoload_extensions('.class.php'); //设定以什么扩展名结尾set_include_path(get_include_path().PATH_SEPARATOR."kakoi/"); //设定文件的目录spl_autoload_register();if(isset($OTHER)){	}else{	$OTHER = "Home";}$build = buildDir::getInstance();//引入文件创建$build->buildFile($OTHER);//创建控制器$build->buildController();//创建配置文件$build->buildConfig();$moudle = isset($_GET['moudle'])?$_GET['moudle']:'Home';$controller = isset($_GET['controller'])?$_GET['controller']:'Index';$method = isset($_GET['method'])?$_GET['method']:'Index';// echo $moudle."
";// echo $controller."
";// echo $method."
";//模板存放路径$path = EVENT."/".$moudle."/View/";$cache = EVENT."/".$moudle."/Cache";$Controller = new Controller();//引入数据库配置文件$data = require_once(EVENT."/Config/Config.php");require_once("/DB/DB.class.php");$DB = new DB($data);require_once("/View/Template.class.php");//引入模板 $arrayConfig = array( "suffix" => ".m", //设置模板文件 "templateDir" => $path, //设置模板所在的文件夹 "compileDir" => $cache, "debug" => false, //设置编译后存放的目录 "cache_htm" => true, //是否需要编译成静态的html文件 "suffix_cache"=> ".htm", //编译后的文件后缀 "cache_time" =>2000, // 多长时间自动更新 "php_turn" =>false, //是否支持原生的php代码 "cache_control" => "control.dat", ); static $tpl;//获取模板对象$tpl = Template::getInstance($arrayConfig);//var_dump($tpl); $handle = handle::getInstance();$handle->C($moudle,$controller,$method);//传入数据库配置参数

Config 文件配置信息

<?php	return array(	'DB_HOST'=>'localhost', 	'DB_USER'=>'root',         //用户名	'DB_PWD'=>'',              //密码	'DB_NAME'=>'test',         //数据库名称	'DB_PORT'=>'3306',         //端口号	'DB_TYPE'=>'mysql',		   //数据库类型	'DB_CHARSET'=>'utf-8',     //字符集	);?>

创建用户的APP文件

<?phpclass buildDir{		static  $content = "<?php	class IndexController{		public function index(){		 echo 'welcome to use kakoi';		}	}	?>";		static $config=	"<?php	return array(	'DB_HOST'=>'localhost', 	'DB_USER'=>'root',         //用户名	'DB_PWD'=>'',              //密码	'DB_NAME'=>'test',         //数据库名称	'DB_PORT'=>'3306',         //端口号	'DB_TYPE'=>'mysql',		   //数据库类型	'DB_CHARSET'=>'utf-8',     //字符集	);?>";	private static $instance = null;	static function getInstance(){		if(self::$instance){				return self::$instance;		}else{			self::$instance = new buildDir();			return self::$instance;		}			}	public function __construct(){							}	//创建文件夹	public function buildFile($path = 'Home'){		//echo  $path;		$this->path = $path;		if(!is_dir(EVENT)) mkdir(EVENT,0775,true);		if(is_writable(EVENT)){						$dirs = array(				EVENT."/".$path,				EVENT."/Public",				EVENT."/Config",				EVENT."/".$path."/Controller",				EVENT."/".$path."/Model",				EVENT."/".$path."/View",				EVENT."/".$path."/Cache",				);			foreach($dirs as $dir){			if(!is_dir($dir))			mkdir($dir,0775,true);									}		}			}	public function buildController()	{		$controller =EVENT."/".$this->path."/"."Controller";		if(is_dir(EVENT."/".$this->path))			if(!is_file($controller."/IndexController.class.php")){				 $temp=$controller."/IndexController.class.php";					$myfile = fopen($temp,"w")or die("Unable to open file!");					fwrite($myfile,buildDir::$content);								}									}	public function buildConfig(){			$data = EVENT."/Config";			if(!is_file($data."/Config.php")){					$temp=$data."/Config.php";					$myfile = fopen($temp,"w")or die("Unable to open file!");					fwrite($myfile,buildDir::$config);			}	}		}

数据库的CURD操作

<?php//数据库连接层class DB{	static $link;	public function __construct($Config=array()){		//数据库连接层		if(count($Config)==0){			echo "数组为空";		}else{			$dsn=$Config['DB_TYPE'].':host='.$Config['DB_HOST'].';dbname='.$Config['DB_NAME'];			self::$link=new PDO($dsn,$Config['DB_USER'], $Config['DB_PWD']);			$this->table = $Config['DB_NAME']."_";					}			}	public function M($table){		$table = strtolower($table);		$this->table.= $table;		}	public function insert($data){			$table =$this->table;			global $key;			global $value;			foreach($data as $key_tmp =>$value_tmp){				$key.=$key_tmp.',';				$value.="'".$value_tmp."'".',';				}			$key=rtrim($key, ",");			$value=rtrim($value, ",");			$sql = "insert into ".$table."(".$key.")values(".$value.")";//sql的插入语句  格式:insert into 表(多个字段)values(多个值)						self::$link->query("SET NAMES utf8");  			$result=self::$link->query($sql);//调用类自身的				//return	$result;	}	public  function update($data){			//$table =$this->table;	 //	指定数据的表			global $field;			foreach($data as $value=>$key){				$field.=$value."="."'".$key."'".",";					}			$field=rtrim($field,",");			echo $field."
"; $this->update = $field; return $this; //将数据存入到 this 中传志 // $sql="update ".$table." set ".$field." where ".$where.""; // echo $sql; // self::$link->query("SET NAMES utf8"); // self::$link->query($sql); } public function where($where){ $sql="update ".$this->table." set ".$this->update." where ".$where.""; self::$link->query("SET NAMES utf8"); $result = self::$link->query($sql); return $result; } public function select(){ self::$link->query("SET NAMES utf8"); $sql = "select * from ".$this->table; $this->sql = $sql; $rs = self::$link->query($sql); $rs->setFetchMode(PDO::FETCH_ASSOC);//返回关联数组 $result = $rs -> fetchAll(); return $result; //return $result; } public function delete($where){ $sql = "delete from ".$this->table." where ".$where."";//sql的插入语句 格式:insert into 表(多个字段)values(多个值) self::$link->query($sql);//调用类自身的 } // public function limit($limit){ // return "123"; // } // public function execute($result = array()){ // var_dump($result); // } //魔术方法实现 public function __call($fun,$args){ if(in_array($fun,array("limit","getField","find"))){ echo $fun."
"; } }}

View层在之前的博客中有提到 链接:View层模板

模板主要是通过INDEX.PHP?moudle?=x&controller=x&method=x

之前考虑用伪静态来实现,后来无论如何接受不到参数就放弃了

代码如下:

 $nav=$_SERVER["REQUEST_URI"];  // echo "request:".$nav."
"; // $script_name=$_SERVER["SCRIPT_NAME"]; // echo "script_name:".$script_name."
"; // $nav1 = str_replace($script_name,"",$nav); // echo $nav1; // $vars = @explode("/",$nav1); //var_dump($vars); // echo $script_name."
"; // echo substr(ereg_replace("$script_name","",urldecode($nav)),1); // echo $script_name; // $nav1=ereg_replace(".html","",substr(ereg_replace("$script_name","",urldecode($nav)),1)); // echo $nav1; // $vars = @explode("/",$nav1); // $_url = array_chunk($vars,3); // $_GET['m'] = $vars[0]?$vars[0]:'index'; //如果没有参数,默认访问index类库的index方法 // $_GET['a'] = $vars[1]?$vars[1]:'index'; // $_GET['d'] = $vars[2]?$vars[2]:'index'; // unset($_url[0]); // if($_url){ // foreach($_url as $key=>$val){ // @$_GET[$val[0]] = $val[1]; // } // }// var_dump($_GET);