依赖注入、MVC和路由的应用--2019-10-11

2019年10月29日 22:14:08阅读数:289博客 / sjgbctjda的博客 / php学习

1、写一个依赖注入的案例, 内容自定义

<?php 

namespace _1011task1;

class sum{
    public function sum($a,$b){
        return $a+$b;
    }
}
// 注入点为构造方法
class test{
    public $test;
    public function __construct($sum){
        $this->test=$sum;
    }
    public function instance(){
        $this->test=$sum;
    }
    public function test($a,$b){
        return $this->test->sum($a,$b);
    }
}
$task1=new test(new sum());
echo $task1->test(1,2);
echo '<hr>';
// 注入点为普通方法
class test1{
    protected $test;
    public function test($sum,$a,$b){
        $this->test=$sum;
        return $this->test->sum($a,$b);
    }
}
$sum=new sum();
$task1=new test1();
echo $task1->test($sum,5,2);

结果:

1011task1.png

2、写一个mvc应用的案例, 内容自定义

model:

<?php
// namespace _1011task2model;
// use PDO;

interface iDb{
    const dsn='mysql:host=127.0.0.1;dbname=video';
    const user='root';
    const pwd='root';
}
// 模型类:数据库查询操作


class model implements iDb{
    protected $pdo=null;
    protected $dsn=iDb::dsn;
    protected $user=iDb::user;
    protected $pwd=iDb::pwd;
    public function __construct(){
        $this->pdo=new PDO($this->dsn,$this->user,$this->pwd);
    } 
    public function select($where='',$table=' staff '){
        $where=empty($where) ? '' : ' WHERE ' .$where;
        $sql=' SELECT * FROM ' .$table.$where;
        $stmt=$this->pdo->prepare($sql);
        $stmt->execute();
        $stmt->fetchAll();
    }
}

view:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <title>Document</title>
</head>
<body>
<div class = "container table-responsive">
<?php
// 视图类:渲染数据
// include 'model.php';
class View
{
    public function fetch($data)
    {   
        $table = '<table class="table table-bordered text-center">';
     
        $table .= '<caption class="text-center"><h3>人员信息表</h3></caption>';
        
        $table .= '<tr><th class="text-center">ID</th><th class="text-center">姓名</th><th class="text-center">年龄</th><th class="text-center">性别</th><th class="text-center">电话</th><th class="text-center">职位</th><th class="text-center">入职时间</th></tr>';
        
        foreach ($data as $info) {
            if($info['sex']==1){
                $gender='男';
            }else{
                $gender='女';
            }
            $date=date('Y-m-d',$info['hiredate']);
            $table .= '<tr>';
            $table .= '<td>' . $info['staff_id'] . '</td>';
            $table .= '<td>' . $info['name'] . '</td>';
            $table .= '<td>' . $info['age'] . '</td>';        
            $table .= '<td>' . $gender . '</td>';
            $table .= '<td>' . $info['mobile'] . '</td>';
            $table .= '<td>' . $info['position'] . '</td>';
            $table .= '<td>' . $date . '</td>';
            $table .= '</tr>';
        }
        $table .= '</table>';
        return $table;
    }
}

?>
</div>
</body>
</html>

controller:

<?php
// namespace _1011task2controller;

require 'model.php';    //引入模型
require 'view.php';     //引入视图

// 门面模式
// 创建服务容器:对象管理容器
class container{
    // 创建对象储存器
    protected $instnace=[];

    //实例化类并保存在$instance数组中
    public function blind($alias,Closure $process){
        $this->instance[$alias]=$process;
    }

    //将对象从数组中取出来
    public function make($alias,$params=[]){
        return call_user_func_array($this->instance[$alias], []);
    }
}

$container=new container();     //创建类实例
// 调用container类中方法,将模型绑定到容器中
$container->blind('model',function(){
    return new model();
});
// 调用container类中方法,将模型绑定到容器中
$container->blind('view',function(){
    return new view();
});
//静态代理
class facade{
    // 创建容器对象
    protected static $container=null;
    // 创建模型数据
    protected static $data=null;
    // 初始化容器
    public static function initialize(container $container){
        static::$container=$container;
    }
    // 将模型中的select()方法静态化(静态代理)
    public static function select(){
        static::$data=static::$container->make('model')->select();
    }
    //将渲染视图中的fecth()方法静态化(静态代理)
    public static function fecth(){
        return static::$container->make('view')->fetch(static::$data);
    }
}
// 声明一个具有实际意义的继承于门面类的子类
class staff extends facade{

}

class controller{
    // 构造方法,初始化容器对象,并注入类中
    public function __construct(container $container){
        staff::initialize($container);
    }
    
    public function instance(){
        // 获取数据
        staff::select();
        // 渲染视图
        return staff::fecth();
    }
}
// 客户端调用
$controller=new controller($container);
echo $controller->instance();
?>

结果:1572333756996817.png

3、写一个简单的路由, 理解路由的原理与目标

<?php
namespace _1011tsak3;

// 从url路径中解析出独立的单元
$uri = $_SERVER['REQUEST_URI'];
echo $uri;

// 将uri中的数据以数组的形式进行保存
$req = explode('/',$uri);
echo '<pre>'.print_r($req,true);

//获取操作模块以及方法
$route = array_slice($req,4,3);     //将数组$req分割,得到想要的数据保存在另一数组中
echo '<pre>'.print_r($route,true),'<br>';

list($module,$controller,$action)=$route;      //将$route数组中的值赋给变量$module,$controller,$action
echo '模块:'.$module.'<br>控制器:'.$controller.'<br>方法:'.$action;

// 获取用户参数
$values=array_slice($req,7,6);
echo '<pre>'.print_r($values,true);
// 将参数以键值对的方式保存在一个数组中
for($i=0;$i<count($values);$i+=2){
    $params[$values[$i]]=$values[$i+1];
}
echo '<pre>'.print_r($params,true);

// 控制器
class user{
    public function add($name,$age,$salary){
        return __METHOD__ . ':姓名:'.$name.',年龄:'.$age.',薪资:'.$salary;
    }
}

echo call_user_func_array([(new user()),'add'],$params);

结果:

1011task3.png

总结:

    1、依赖注入:将对象作为参数来使用。可以在一定程度上减少代码的耦合度,防止在类的内部对其它类的依赖关系,而是作为一个外部参数进行注入,便于代码维护。

    2、容器管理:用一个专门的类来管理依赖注入的参数的创建和使用,感觉还不是很懂,还需要在多了解一下。

    3、门面模式:在容器和控制器中间添加一个中间层:用来将被注入的参数中的方法变成静态方法。门面的添加只是为了使控制器中的代码变得更加简单,对于代码之间的耦合关系影响不大。

    4、路由管理:将用户输入的url地址进行解析,从而调用对应的模型和方法,实现用户的需求。

    

    


批改状态:合格

老师批语:合格

版权申明:本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!

全部评论

文明上网理性发言,请遵守新闻评论服务协议

条评论
  • 博主信息
    sjgbctjda的博客
    博文
    22
    粉丝
    0
    评论
    0
    访问量
    8459
    积分:0
    P豆:46