第一章 框架说明
1-1课程说明:
从零开始打造自己的PHP框架(上)
为什么要开发自己的框架呢?
1、为了更快的开发效率
2、为了更高的运行效率
3、为了更好的证明自己
开发框架 需要做到那几点?
1、能够熟练的使用PHP
2、较为深刻的理解面向对象和MVC概念
3、较强的逻辑能力和动手能力
1-2:框架的运行流程
入口文件 -> 定义常量 -> 引入函数库 -> 自动加载类 -> 启动框架
<- 路由解析 <-加载控制器 <-返回结果
第二章 框架搭建
2-1入口文件:
路径+文件名:./index.php
内容:
代码:
/*
入口文件
1、定义常量
2、加载函数库
3、启动框架
*/
define('IMOOC',realpath('./'));
define('CORE',IMOOC.'/core');
define('APP',IMOOC.'/app');
define('DEBUG',true);
if(DEBUG){
ini_set('display_error','On');
} else {
ini_set('display_error','Off');
}
// include CORE.'/common/function.php';
include '/core/common/function.php';
// p(IMOOC);
// include CORE.'/imooc.php';
include '/core/imooc.php';
\core\imooc::run();
路径+文件名:./core/common/function.php
P方法:
作用:输出对应变量或数组
代码:function P($var){
if(is_bool($var)){
var_dump($var);
}else if(is_null($var)){
var_dump(NULL);
}else{
echo "<pre style='position:relative;z-index:1000;padding:10px;
border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;
line-height:18px;opacity:0.9;'>".print_r($var,true)."</pre>";
}
}
路径+文件名:./core/imooc.php
内容:
2-2自动加载
路径+文件名:./index.php
新+一行代码:
spl_autoload_register('\core\imooc::load');
路径+文件名:./core/imooc.php
在run方法中加入:
$route = new \core\route();//实例化
然后 新+一个Load方法:
代码:
static public function load($class){
//自动加载类
if(isset($classMap[$class])){
return true;
}else{
$class = str_replace('\\', '/', $class);
$file = IMOOC.'/'.$class.'.php';
if(is_file($file)){
include $file;
self::$classMap[$class] = $class;
}else{
return false;
}
}
}
路径+文件名:./core/route.php
内容:
2-3路由:
在core文件夹中新建一个lib文件夹,在将route.php文件移入lib文件夹内。
然后修改文件:./core/lib/route.php
修改为:
代码:
<?php
namespace core\lib;
class route{
public $ctrl;
public $action;
public function __construct(){
// P($_SERVER);
if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/'){
$path = $_SERVER['REQUEST_URI'];
$patharr = explode('/', trim($path,'/'));
// P($patharr);
if(isset($patharr[2])){
$this->ctrl = $patharr[2];
}else{
$this->ctrl = 'index';
}
unset($patharr[2]);
if(isset($patharr[3])){
$this->action = $patharr[3];
unset($patharr[3]);
}else{
$this->action = 'index';
}
// P($patharr);
//url多余部分转化成 GET
$count = count($patharr)+2;
// echo $count;die;
$i = 4;
while($i<$count){
if(isset($patharr[$i+1])){
$_GET[$patharr[$i]] = $patharr[$i+1];
}
$i = $i+2;
}
}else{
$this->ctrl = 'index';
$this->action = 'index';
}
}
}
?>
下一步:在根目录穿件一个.htaccess
文件内容:
<IFModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$i [QSA,PT,L]
</IFModule>
2-4加载控制器
第一步:在app目录下创建一个ctrl目录
在里面创建一个indexCtrl.php
第二步:在入口文件index.php中 自定义一个变量
Define(‘APP’,IMOOC.’/app’)
第三步:imooc.php run方法
2-5模型类
第一步:通过控制器 操作数据库
indexCtrl.php
第二步:创建一个\core\lib\model.php
2-6试图类
第一步:
控制器indexCtrl.php:
第二步:
Imooc.php
添加一个公共变量:public $assign;
在imooc类中添加2个方法:
第三步:
在app文件夹中添加一个views文件夹,然后创建一个index.hmtl文件
2-7框架回顾
经过上述2-1~2-6总共6小节的造作,一个简单的框架已经完成。