PHP_MVC design pattern 02

Today 1.1 goals

  1. Understand the concept based on a single entry MVC project ideas;
  2. Grasp the practical application of project single-entry;
  3. Grasp the core architecture framework;
  4. DAO classes understand the role of master packages DAO;
  5. Understand the role of trait;
  6. Public understanding of the role model, the model of public control package;
  7. Understand the role of each directory and directory structure MVC frame design;
  8. Understand the role of the configuration file;

1.2 Framework directory

1.2.1 Creating the directory structure

1.2.2 documents classified storage

The last lecture of classified documents stored in different directories

The files stored in different directories later, because the class file address has changed, it is not done automatically load the class, then the main task today is to focus on how to achieve the kind of automatic loading started.

Because every request entry file, so. "" Represents the directory where the file entry

1.3 add a namespace

Do namespace through the file directory address, so you can get to know the address of the namespace file storage.

Model.class.php

namespace Core;
class Model {
    ...

MyPDO.class.php

namespace Core;
class MyPDO{
    ...

ProductsModel.class.php

<?php
namespace Model;
//products模型用来操作products表
class ProductsModel extends Model{
    ...

ProductsController.class.php

<?php
namespace Controller\Admin;
//商品模块
class ProductsController {
    ...

1.4 Framework class implementation

1.4.1 constants defined path

Since the file path high frequency of use, and the long path, so the path of the fixed path defined constants

Knowledge Point

1、getcwd():入口文件的绝对路径
2、windows下默认的目录分隔符是`\`,Linux下默认的目录分隔符是`/`。DIRECTORY_SEPARATOR常量根据不同的操作系统返回不同的目录分隔符。

Code

Created under the Core folder Framework.class.php

private static function initConst(){
    define('DS', DIRECTORY_SEPARATOR);  //定义目录分隔符
    define('ROOT_PATH', getcwd().DS);  //入口文件所在的目录
    define('APP_PATH', ROOT_PATH.'Application'.DS);   //application目录
    define('CONFIG_PATH', APP_PATH.'Config'.DS);
    define('CONTROLLER_PATH', APP_PATH.'Controller'.DS);
    define('MODEL_PATH', APP_PATH.'Model'.DS);
    define('VIEW_PATH', APP_PATH.'View'.DS);
    define('FRAMEWORK_PATH', ROOT_PATH.'Framework'.DS);
    define('CORE_PATH', FRAMEWORK_PATH.'Core'.DS);
    define('LIB_PATH', FRAMEWORK_PATH.'Lib'.DS);
    define('TRAITS_PATH', ROOT_PATH.'Traits'.DS);
}

1.4.2 introduced profile

1. Create config.php in the config directory

<?php
return array(
    //数据库配置
    'database'=>array(),
    //应用程序配置
    'app'       =>array(
        'dp'    =>  'Admin',        //默认平台
        'dc'    =>  'Products',     //默认控制器
        'da'    =>  'list'          //默认方法
    ),
);

2, is introduced in the frame profile class

private static function initConfig(){
   $GLOBALS['config']=require CONFIG_PATH.'config.php';
}

Question: Why is not stored in the configuration file constants?

A: Because before 7.0, constants arrays and objects can not be saved.

1.4.3 determine the route

p: [platform] platform

c: controller [controller]

a: action [Method]

1561431781576

private static function initRoutes(){
    $p=$_GET['p']??$GLOBALS['config']['app']['dp'];
    $c=$_GET['c']??$GLOBALS['config']['app']['dc'];
    $a=$_GET['a']??$GLOBALS['config']['app']['da'];
    $p=ucfirst(strtolower($p));
    $c=ucfirst(strtolower($c));		//首字母大写
    $a=strtolower($a);			//转成小写
    define('PLATFROM_NAME', $p);    //平台名常量
    define('CONTROLLER_NAME', $c);  //控制器名常量
    define('ACTION_NAME', $a);      //方法名常量
    define('__URL__', CONTROLLER_PATH.$p.DS);   //当前请求控制器的目录地址
    define('__VIEW__',VIEW_PATH.$p.DS);     //当前视图的目录地址
}

1.4.4 Automatic load class

private static function initAutoLoad(){
    spl_autoload_register(function($class_name){
        $namespace= dirname($class_name);   //命名空间
        $class_name= basename($class_name); //类名
        if(in_array($namespace, array('Core','Lib')))   //命名空间在Core和Lib下
            $path= FRAMEWORK_PATH.$namespace.DS.$class_name.'.class.php';
        elseif($namespace=='Model')     //文件在Model下
            $path=MODEL_PATH.$class_name.'.class.php';
        elseif($namespace=='Traits')    //文件在Traits下
            $path=TRAITS_PATH.$class_name.'.class.php';
        else   //控制器
            $path=CONTROLLER_PATH.PLATFROM_NAME.DS.$class_name.'.class.php'; 
        if(file_exists($path) && is_file($path))
            require $path;
    });
}

1.4.5 request distribution

private static function initDispatch(){
    $controller_name='\Controller\\'.PLATFROM_NAME.'\\'.CONTROLLER_NAME.'Controller';	//拼接控制器类名
    $action_name=ACTION_NAME.'Action';	//拼接方法名
    $obj=new $controller_name();
    $obj->$action_name();
} 

1.4.6 Packaging run () method

class Framework{
    //启动框架
    public static function run(){
        self::initConst();
        self::initConfig();
        self::initRoutes();
        self::initAutoLoad();
        self::initDispatch();
    }
    ...

1.4.7 call inlet run () method

<?php
require './Framework/Core/Framework.class.php';
Framework::run();

run () method call after the start of the frame.

1.5 Running the Project

1, parameters obtained from the database connection profile

class Model {
   ...
   //连接数据库
   private function initMyPDO() {
      $this->mypdo= MyPDO::getInstance($GLOBALS['config']['database']);
   }
}

2, the controller changes ProductsControleller

<?php
namespace Controller\Admin;
//商品模块
class ProductsController {
	//获取商品列表
	public function listAction() {
            //实例化模型
            $model=new \Model\ProductsModel();
            $list=$model->getList();
            //加载视图
            require __VIEW__.'products_list.html';
	}
	//删除商品
	public function delAction() {
		...
		$model=new \Model\ProductsModel();
		...
	}
}

3, change class ProductsModel

<?php
namespace Model;
class ProductsModel extends \Core\Model{
	
}

4, change MyPDO class

...
private function fetchType($type){
    switch ($type){
        case 'num':
            return \PDO::FETCH_NUM;
        case 'both':
            return \PDO::FETCH_BOTH;
        case 'obj':
            return \PDO::FETCH_OBJ;
        default:
             return \PDO::FETCH_ASSOC;
    }
}
...
//所有的内置类都在公共的命名空间下。

Test success

1.6 traits code reuse

Some controllers After the operation you want to jump, others do not,

Resolution: The method forwards the package to the traits.

Code

1, the prepared pictures are copied to the Public directory

2. Create a directory Jump.class.php in Traits

<?php
//跳转的插件
namespace Traits;
trait Jump{
    //封装成功的跳转
    public function success($url,$info='',$time=1){
        $this->redirect($url, $info, $time, 'success');
    }
    //封装失败跳转
    public function error($url,$info='',$time=3){
        $this->redirect($url, $info, $time, 'error');
    }
    /*
     * 作用:跳转的方法
     * @param $url string 跳转的地址
     * @param $info string 显示信息
     * @param $time int 停留时间
     * @param $flag string 显示模式  success|error
     */
    private function redirect($url,$info,$time,$flag){
        if($info=='')
            header ("location:{$url}");
        else{
          echo <<<str
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
    <!--
    <meta http-equiv="refresh" content="3;http://www.php.com"/>
    -->
	<title>Document</title>
<style>
body{
	text-align: center;
	font-family: '微软雅黑';
	font-size: 18px;
}
#success,#error{
	font-size: 36px;
	margin: 10px auto;
}
#success{
	color: #090;
}
#error{
	color: #F00;
}
</style>
</head>
<body>
	<img src="/Public/images/{$flag}.fw.png">
	<div id='{$flag}'>{$info}</div>
	<div><span id='t'>{$time}</span>秒以后跳转</div>
</body>
</html>
<script>
window.onload=function(){
	var t={$time};
	setInterval(function(){
		document.getElementById('t').innerHTML=--t;
		if(t==0)
			location.href='index.php';
	},1000)
}
</script>
str;
        exit;
        }
    }
}

In the prototype controller ProductsController

namespace Controller\Admin;
//商品模块
class ProductsController{
    use \Traits\Jump;   //复用代码
    ...

1.7 Delete function

Entrance

<a href="index.php?p=Admin&c=Products&a=del&proid=<?=$rows['proID']?>" onclick="return confirm('确定要删除吗')">删除</a>

Controller (ProductsController)

public function delAction() {
   $id=(int)$_GET['proid'];	//如果参数明确是整数,要强制转成整形
   $model=new \Model\ProductsModel();
   if($model->del($id))
       $this->success('index.php?p=Admin&c=Products&a=list', '删除成功');
   else 
       $this->error('index.php?p=admin&c=Products&a=list', '删除失败');
}

Model, View

无改变

1.8 Job

1, modify

2, add

Guess you like

Origin www.cnblogs.com/xeclass/p/12657485.html