批改状态:合格
老师批语:
一.单例模式: 一个类仅允许被实例化一次
1.简单的单例模式的实现
<?php
class Config
{
/**
* 为什么要用静态的? 因为静态属性于类的,被所有类实例所共享;
* 为什么要能实例初始化为null? 便于检测
*/
private static $instance = null; // 其实默认值也是null,可以省
// 配置参数容器
public $setting = [];
// 禁止从类的外部实例化对象
private function __construct()
{
}
//克隆方法也私有化
private function __clone()
{
// TODO: Implement __clone() method.
}
//外部仅允许通过一个公共静态方法来创建实例
public static function getInstance()
{
//检测当前的类属性$instance是否已经保存了当前类的实例?
if (self::$instance == null) {
self::$instance = new self();
}
// 如果已经存在当前类的实例,返回当前类的实例
return self::$instance;
}
}
$test1=Config::getInstance();
$test2=Config::getInstance();
var_dump($test1,$test2);
var_dump($test1==$test2);//输出结果是true点击 "运行实例" 按钮查看在线实例
2.单例实现配置类
<?php
class Config
{
/**
* 为什么要用静态的? 因为静态属性于类的,被所有类实例所共享;
* 为什么要能实例初始化为null? 便于检测
*/
private static $instance = null; // 其实默认值也是null,可以省
// 配置参数容器
public $setting = [];
// 禁止从类的外部实例化对象
private function __construct()
{
}
//克隆方法也私有化
private function __clone()
{
// TODO: Implement __clone() method.
}
//外部仅允许通过一个公共静态方法来创建实例
public static function getInstance()
{
//检测当前的类属性$instance是否已经保存了当前类的实例?
if (self::$instance == null) {
self::$instance = new self();
}
// 如果已经存在当前类的实例,返回当前类的实例
return self::$instance;
}
//设置配置项的操作
public function set()
{
//获取参数的数量
$num = func_num_args();
if ($num > 0) {
switch ($num) {
case 1: // 如果只有一个参数,说明这是一个数组
$value = func_get_arg(0);
if (is_array($value)) {
$this->setting = array_merge($this->setting, $value);
}
break;
case 2: // 逐个设置
$name = func_get_arg(0); // 配置项的名称
$value = func_get_arg(1); // 配置项的值
$this->setting[$name] = $value;
break;
default:
echo '<span style="color:red">非法参数</span>';
}
} else {
echo '<span style="color:red">没有参数</span>';
}
}
//获取参数,当五参数输入的话,默认获取全部的参数
public function get($name=''){
if(empty($name)){
return $this->setting;
}else{
return $this->setting[$name];
}
}
}
$test1=Config::getInstance();
$test1->set('host','127.0.0.1');//逐个设置
echo $test1->get('host');//输出结果 127.0.0.1
echo '<hr>';
$config = ['host'=>'localhost','user'=>'root','pass'=>'123456'];
$test1->set($config);
print_r($test1->get());//输出结果:Array ( [host] => localhost [user] => root [pass] => 123456 )点击 "运行实例" 按钮查看在线实例
二:工厂模式: 不用用new ,而用函数/类方法批量创建对象
<?php
/**
* 工厂模式: 不用用new ,而用函数/类方法批量创建对象
* $obj = create($class)
*/
// 声明一个类: 形状
class Shape
{
// 声明一个静态方法,用来创建对象的,$type 就是类
public static function create($type,array $size=[])
{
//检测形状
switch ($type)
{
//长方形
case 'rectangle':
//创建出长方形的对象
return new Rectangle($size[0], $size[1]);
break;
//长方形
case 'triangle':
//创建出长方形的对象
return new Rriangle($size[0], $size[1]);
break;
}
}
}
// 声明一个长方形类
class Rectangle
{
private $width; // 宽
private $height; // 高
public function __construct($width, $height)
{
$this->width = $width;
$this->height = $height;
}
//计算面积
public function area()
{
return $this->width * $this->height;
}
}
// 声明一个三角形类
class Rriangle
{
private $bottom; // 底
private $height; // 高
public function __construct($bottom, $height)
{
$this->bottom = $bottom;
$this->height = $height;
}
//计算面积
public function area()
{
return ($this->bottom * $this->height)/2;
}
}
$rectangle = Shape::create('rectangle',[10,30]);
echo '长方形的面积是: '. $rectangle->area(), '<hr>';
$triangle = Shape::create('triangle',[20,50]);
echo '三角形的面积是: '. $triangle->area(), '<hr>';点击 "运行实例" 按钮查看在线实例
三.注册树: 就是创建一个对象集合/对象池/对象树,对象容器来存储对象
<?php
// 先声明三类个,一会让他们上树
class Demo1 {};
class Demo2 {};
class Demo3 {};
// 声明一个对象注册树
class Register
{
// 保存着已经挂到树上的对象
public static $objs = [];
// 将对象挂到树上
public static function set($index, $obj)
{
self::$objs[$index] = $obj;
}
// 取出对象来用一下
public static function get($index)
{
return self::$objs[$index];
}
// 销毁对象
public static function del($index)
{
unset(self::$objs[$index]);
}
}
// 将三个类的对象上树
Register::set('demo1', new Demo1);
Register::set('demo2', new Demo2);
Register::set('demo3', new Demo3);
// 检测
var_dump(Register::$objs);
//结果
// D:\phpStudy\WWW\phpcn\test.php:38:
// array (size=3)
// 'demo1' =>
// object(Demo1)[1]
// 'demo2' =>
// object(Demo2)[2]
// 'demo3' =>
// object(Demo3)[3]
//查看
//var_dump(Register::$objs['demo2']);
var_dump(Register::get('demo1'));
// 删除
//Register::del('demo3');
var_dump(Register::get('demo3'));点击 "运行实例" 按钮查看在线实例
四.mvc原理和简单实现(model,controller,view)
1.controller
<?php
/**
*控制器类
*/
namespace mvc\controller;
use mvc\model\Model;
use mvc\view\View;
class Controller
{
public function index()
{
require './model/Model.php';
$model = new Model('php','root','root');
$model->select('staff', 10);
$result = $model->result;
require './view/View.php';
$view = new View($result);
$data = $view->getData();
$view->display($data);
}
}点击 "运行实例" 按钮查看在线实例
2.model
<?php
//模型类
namespace mvc\model;
class Model
{
public $pdo = null;
//连接数据库
public $result = [];
public function __construct($dbname, $user, $pass)
{
$this->pdo = new \PDO('mysql:host=127.0.0.1;dbname='.$dbname, $user, $pass);
}
//查询
public function select($table, $num)
{
//创建预处理对象
$stmt = $this->pdo->prepare("SELECT `id`,`name`,`age`,`salary` FROM {$table} LIMIT :num");
//执行查询
$stmt->bindValue(':num', $num, \PDO::PARAM_INT);
$stmt->execute();
$this->result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
3.view
<?php
/**
*视图类
*/
namespace mvc\view;
class View
{
public $data = [];
//模板赋值
public function __construct($data)
{
$this->data = $data;
}
//获取数据
public function getData()
{
return $this->data;
}
//渲染模板
public function display($data)
{
$table = '<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
table,th,td {
border: 1px solid black;
}
table {
border-collapse: collapse; /*折叠表格线*/
width: 600px;
margin: 30px auto;
text-align: center;
padding: 5px;
}
table tr:first-child {
background-color: lightgreen;
}
table caption {
font-size: 1.5em;
margin-bottom: 15px;
}
</style>
<title>MVC简介</title>
</head>
<body>
<table>
<caption>员工信息表</caption>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>工资</th>
</tr>';
foreach ($data as $staff) {
$table .= '<tr>';
$table .= '<td>'.$staff['id'].'</td>';
$table .= '<td>'.$staff['name'].'</td>';
$table .= '<td>'.$staff['age'].'</td>';
$table .= '<td>'.$staff['salary'].'</td>';
$table .= '</tr>';
}
$table .= '</table></body></html>';
echo $table;
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号