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

index.php 公共部分

<?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';
    }
}

代理模式(比如主从数据库选择问题,主库写、从库读)

一般编程实现

<?php
$db = \Frame\Factory::getDatabase('slave');//选择从库
$res = $this->db->query("SELECT username FROM user WHERE id=$id");
$db = \Frame\Factory::getDatabase('master');//选择主库
$res = $this->db->query("UPDATE user SET username = 'lili' WHERE id=$id");

代理模式实现

以查询或者更新一个user表的字段例子新建IUserProxy.php接口类约束

<?php
namespace Frame;

interface IUserProxy
{
    function getUserName($id);
    function setUserName($id, $name);
}

新建代理类实现IUserProxy.php接口

<?php
namespace Frame\Database;

use Factory;

class Proxy
{
    function query($sql)
    {
        if (substr($sql, 0, 6) == 'select')
        {
            echo "读操作:$sql<br />";
            return Factory::getDatabase('slave')->query($sql);
        }
        else
        {
            echo "写操作:$sql<br />";
            return Factory::getDatabase('master')->query($sql);
        }
    }
}

在Factory.php类文件中修改

<?php
namespace Frame;

class Factory
{
    static $proxy = null;
    /**
     * @param $id
     * @return User
     */
    static function getUser($id)
    {
        $key = 'user_'.$id;
        $user = Register::get($key);
        if (!$user) {
            $user = new User($id);
            Register::set($key, $user);
        }
        return $user;
    }

    /**
     * @param $name
     * @return bool
     */
    static function getModel($name)
    {
        $key = 'app_model_'.$name;
        $model = Register::get($key);
        if (!$model) {
            $class = '\\App\\Model\\'.ucwords($name);
            $model = new $class;
            Register::set($key, $model);
        }
        return $model;
    }

    static function getDatabase($id = 'proxy')
    {
        if ($id == 'proxy')
        {
            if (!self::$proxy)
            {
                self::$proxy = new \IMooc\Database\Proxy;
            }
            return self::$proxy;
        }
    }
}

在index.php中调用

<?php
define('BASEDIR',__DIR__);
include BASEDIR.'/Frame/Loader.php';
spl_autoload_register('\\Frame\\Loader::autoload');
$proxy = new \Frame\Database\Proxy();
$proxy->query("SELECT * FROM user WHERE id = 1");
$proxy->query("UPDATE user SET username='lll' WHERE id=1");
Last modification:September 3, 2022
如果觉得我的文章对你有用,请随意赞赏