本次代码符合PHP规范PRS_0
根目录下新建一个Frame的目录(核心目录),建立APP目录(项目目录)
统一访问入口文件index.php,建立类文件Loader.php(用于自动加载类)

index.php 公共部分

define('BASEDIR',__DIR__);
include BASEDIR.'/Frame/Loader.php';
spl_autoload_register('\\Frame\\Loader::autoload');

Loader.php

<?php

namespace Frame;

class Loader
{
    static function autoload($class)
    {
        require  BASEDIR.'/'.str_replace('\\','/',$class).'.php';
    }
}

数据对象映射模式

创建一个User.php类文件 映射test数据库的user表,对数据表操作

<?php

namespace Frame;

class User
{
    //映射数据库字段
    public $id;//主键ID
    public $class;//班级
    public $grade;//年纪
    public $score;//成绩
    public $username;//姓名

    protected $db;

    public function __construct($id)
    {
        $this->db = new \Frame\Database\Mysqli();
        $this->db->connect('127.0.0.1', 'root', 123456, 'test');
        $res = $this->db->query("SELECT * FROM user WHERE id=$id");
        $data = $res->fetch_assoc();
        $this->id = $data['id'];
        $this->class = $data['class'];
        $this->grade = $data['grade'];
        $this->score = $data['score'];
        $this->username = $data['username'];
    }

    /**
     * 见,对象销毁的顺序,默认情况下,跟其创建的顺序相反;
     */
    public function __destruct()
    {
        $this->db->query("UPDATE user SET username= '{$this->username}',
        class={$this->class},grade={$this->grade},score={$this->score} WHERE id={$this->id}");
        $this->db->close();
    }
}

在index.php中调用

<?php
define('BASEDIR',__DIR__);
include BASEDIR.'/Frame/Loader.php';
spl_autoload_register('\\Frame\\Loader::autoload');
$user = new \Frame\User(1);
//var_dump($user->id, $user->username);//读取字段
//更新字段
$user->class = 2;
$user->username = "test";
$user->grade = 3;
$user->score = 99;

数据对象映射模式、工厂模式、注册树模式结合(对数据库中的两个字段修改,)
给工厂类添加一个方法

<?php

namespace Frame;
class Factory
{
    static public function  createDatabase()
    {
       $db = Database::getInstance();
       Register::set('db1', $db);
       return $db;
    }
    //添加的方法
    static public function getUser($id)
    {
        $key = 'user_'.$id;//别名
        $user = Register::get($key);//注册树/注册器
        if (!$user) {
            $user = new User($id);
            Register::set($key, $user);
        }
        return $user;
    }
}

在index.php中调用

<?php
define('BASEDIR',__DIR__);
include BASEDIR.'/Frame/Loader.php';
spl_autoload_register('\\Frame\\Loader::autoload');
class Page
{
    public function index()
    {
        //$user = new Frame\User(1);
        $user = Frame\Factory::getUser(1);//工厂模式
        $user->username = "k444";
        //$this->test();//这样写不行,析构函数是反向销毁对象的
    }

    public function test()
    {
        //$user = new Frame\User(1);
        $user = Frame\Factory::getUser(2);//工厂模式
        $user->class = 2;
    }

}
$page = new Page();
$page->index();//修改username
$page->test();//修改class

关注友儿不迷路

Last modification:September 6th, 2020 at 10:20 am
如果觉得我的文章对你有用,请随意赞赏