シングルエントリ MVC 構造を実装するための PHP ソース コード メソッド

不言
リリース: 2023-04-02 10:56:01
オリジナル
2022 人が閲覧しました

この記事では主に PHP ソース コードに単一エントリの MVC 構造を実装する方法を紹介します。これには一定の参考価値があります。今、あなたに共有します。必要な友人はそれを参照できます。

メイン:

  1. MVC ディレクトリ構造

  2. データベース ツール クラスの作成

  3. パブリック モデル クラスとパブリック コントローラーの作成クラス

--------------:--------------------------------------
blog
├─index.php  入口文件
├─Model 模型
│  └─UserModel.class.php 用户模型类
├─View 视图
│  └─login.html  登录表单页面
├─Controller 控制器
│  └─UserController.class.php 用户控制器
├─Frame 公共使用的类
│   ├─BaseModel.class.php 数据库连接类
│   ├─BaseController.class.php 控制器公共操作(设置编码,信息跳转)
│   └─Db.class.php 数据库操作工具类
└─Public   静态公共文件(js,css,images)
    ├─js/   js文件
    ├─css/  css样式文件
    └─images img图片
-----------------------------------------------------------------
ログイン後にコピー

MVC ディレクトリ構造

1) 準備: ブランチの作成

1 $ git checkout master2 $ git checkout -b "mvc-dbtools-base"
ログイン後にコピー

2) ディレクトリ構造の作成:

MVC ディレクトリ: Model/Controller/ View/

静的リソース ディレクトリ: Public/

3) プロジェクト エントリ ファイル [index.php] を作成します

のエンコーディングをコピーしますオリジナルのlogin.php header(...)

作成したコントローラUserControllerとモデルUserModelの紹介

 1 <?php 
 2 /** 
 3  * 入口文件 
 4  */ 
 5 header("content-type:text/html;charset=utf-8"); 
 6  
 7 require_once(&#39;Model/UserModel.class.php&#39;); 
 8 require_once &#39;Controller/UserController.class.php&#39;; 
 9 
 10 //实例化控制器
 11 $userCtr = new UserController();
 12 
 13 $a = !empty($_GET[&#39;a&#39;]) ? $_GET[&#39;a&#39;] : &#39;login&#39;;
 14 
 15 $userCtr -> $a();
ログイン後にコピー

4) コントローラUserControllerの作成 【Controller/UserController.class.php】

 1 <?php 
 2 /** 
 3  * UserController.class.php 用户控制器 
 4  */ 
 5  
 6 class UserController { 
 7     /** 
 8      * 展示登录界面 
 9      * @access public
 10      */
 11     public function login()
 12     {
 13         include "View/login.html";
 14     }
 15 
 16     /**
 17      * 登录操作: 校验登录信息
 18      */
 19     public function dlogin()
 20     {
 21         //接收登录信息
 22         $data = array();
 23         $data[&#39;username&#39;] = trim($_POST[&#39;username&#39;]);
 24         $data[&#39;pwd&#39;] = trim($_POST[&#39;pwd&#39;]);
 25 
 26         //实例化模型,调用模型方法,校验用户名和密码
 27         $model = new UserModel();
 28         $result = $model->checkLoginInfo($data);
 29 
 30         //结果提示信息
 31         if($result){
 32             exit(&#39;登录成功&#39;);
 33         } else {
 34             echo "用户名或密码不正确!";
 35             header(&#39;refresh:3; url=?&#39;);
 36         }
 37     }
 38 }
ログイン後にコピー

5) ユーザーモデルクラスの作成 UserModel [Model/UserModel.class.php]

実装メソッド:checkLoginInfo() ユーザー名とパスワードの確認

<?php/**
 * UserModel.class.php
 *     用户模型类-操作表pbg_users */class UserModel
{    /**
     * 检验登录信息
     * @param  array $data 用户提交的登录信息
     * @return bool       
     true-校验成功 false-校验失败     */
    public function checkLoginInfo($data)
    {        //连接数据库
        $conn = @mysql_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;root&#39;) or die(&#39;连接数据库失败!&#39;);        
        mysql_query(&#39;set names utf8&#39;,$conn);        
        mysql_query(&#39;use web&#39;,$conn);        //查询数据库
        $sql = "select username,pwd from pbg_users where username=&#39;{$data[&#39;username&#39;]}&#39;";        
        $res = mysql_query($sql,$conn);        //登录结果提示信息
        if($res !== false){            
        $user = mysql_fetch_array($res);            
        if( $user[&#39;pwd&#39;] == md5($data[&#39;pwd&#39;]) ){                
        return true;
            }
        }        return false;
    }
}
ログイン後にコピー

ユーザーモデルクラスの表示

6) ログインビュー: [view/login.html]

導入パスの変更、

フォーム送信アクションの変更: action=?a =dlogin

 1 <!DOCTYPE html> 
 2 <html lang="zh-CN"> 
 3 <head> 
 4     <meta charset="UTF-8"> 
 5     <title>登录</title> 
 6     <link rel="stylesheet" type="text/css" href="public/layui/css/layui.css"> 
 7     <link rel="stylesheet" type="text/css" href="public/css/style.css"> 
 8 </head> 
 9 <body>
 10 <p class="container">
 11     <p class="content">
 12         <form action="?a=dlogin" class="layui-form" method="post">
 13             <p class="layui-form-item">
 14                 <h2>登录</h2>
 15             </p><hr>
 16 
 17             <p class="layui-form-item">
 18                 <label class="layui-form-label">用户名:</label>
 19                 <p class="layui-input-block">
 20                     <input type="text" name="username" class="layui-input" required  lay-verify="required"  placeholder="请输入用户名" autocomplete="off" >
 21                 </p>22             </p>23 24             <p class="layui-form-item">25                 <label class="layui-form-label">密   码:</label>
 26                 <p class="layui-input-block">27                     <input type="password" name="pwd" required lay-verify="required" placeholder="请输入密码"  class="layui-input">
 28                 </p>29             </p>30 31             <p class="layui-form-item">
 32                 <p class="layui-input-block">
 33                     <button  lay-submit class="layui-btn">登录</button>
 34                     <button type="reset" class="layui-btn layui-btn-primary">重置</button>
 35                 </p>36             </p>37         </form>38     </p>39 </p>40 <script type="text/javascript" src="public/layui/layui.js"></script>41 <script>
 42     layui.use(&#39;form&#39;, function(){43         var form = layui.form;44     });45 </script>46 </body>47 </html>
ログイン後にコピー


クリックしてログイン ビューのソース コードを表示します

データベース接続操作はすべてモデル内にあり、抽出できますデータベース操作ツールクラスの作成

データベースツールクラスの作成

データベース接続、エンコーディングの設定、データベースの選択

シングルトンの実装

データを1行取得 getOneRow 、単一の配列の取得 getOneData、複数の行の取得 getAllRows、追加、削除、変更 exec

挿入または更新ステートメントを自動的に生成 autoExecute()

[Frame/Db.class.php]

  1 <?php 
  2  /**  
  3   * Db.class.php 数据库操作工具类  
  4   * @author young  
  5   */  
  6    
  7  class Db  
  8  {  
  9      private $host; //主机 
  10      private $user; //用户名 
  11      private $pwd; //密码 
  12      private $port; //端口 
  13      private $charset; //编码 
  14      private $dbname; //数据库 
  15  
  16      private $link=null; //存储数据库资源 
  17      private static $instance=null; //存储本类实例对象 
  18  
  19      /** 
  20       * 构造方法: 保存数据库连接信息,连接数据库 
  21       * @access private 
  22       * @param array $conf 数据库连接信息 
  23       */ 
  24      private function __construct($conf) 
  25      { 
  26          $this->host = !empty($conf[&#39;host&#39;]) ? $conf[&#39;host&#39;] : &#39;localhost&#39;; 
  27          $this->user = !empty($conf[&#39;user&#39;]) ? $conf[&#39;user&#39;] : &#39;root&#39;; 
  28          $this->pwd = !empty($conf[&#39;pwd&#39;]) ? $conf[&#39;pwd&#39;] : &#39;root&#39;; 
  29          $this->port = !empty($conf[&#39;port&#39;]) ? $conf[&#39;port&#39;] : &#39;3306&#39;; 
  30          $this->charset = !empty($conf[&#39;charset&#39;]) ? $conf[&#39;charset&#39;] : &#39;utf8&#39;; 
  31          $this->dbname = !empty($conf[&#39;dbname&#39;]) ? $conf[&#39;dbname&#39;] : &#39;web&#39;; 
  32  
  33          $this->connect(); 
  34      } 
  35  
  36      /** 
  37       * 连接数据库,设置编码,选库 
  38       * @access private 
  39       */ 
  40      private function connect() 
  41      { 
  42          $this->link = @ mysql_connect("{$this->host}:{$this->port}", "$this->user", "$this->pwd") or die(&#39;连接失败!&#39;.mysql_error()); 
  43          $this->setCharset($this->charset); 
  44          $this->useDb($this->dbname); 
  45      } 
  46      /** 
  47       * 设置字符便 
  48       * @access public 
  49       * @param string $char 字符编码 
  50       */ 
  51      public function setCharset($char) 
  52      { 
  53          $this->query("set names $char"); 
  54      } 
  55      /** 
  56       * 选择数据库 
  57       * @access public 
  58       * @param string $dbname 数据库名称 
  59       */ 
  60      public function useDb($dbname) 
  61      { 
  62          $this->query("use $dbname"); 
  63      } 
  64  
  65      /** 
  66       * 执行sql语句 
  67       * @param  string $sql sql语句 
  68       * @return mixed 
  69       */ 
  70      private function query($sql) 
  71      { 
  72          $result = mysql_query($sql, $this->link); 
  73          if(false === $result) { 
  74              echo "<p>sql执行失败!<br>"; 
  75              echo "<br>失败语句:".$sql; 
  76              echo "<br>错误代号".mysql_errno(); 
  77              echo "<br>错误提示: ".mysql_error()."</p>"; 
  78              exit(); 
  79          } 
  80          return $result; 
  81      } 
  82  
  83      /** 
  84       *  获取本类实例 
  85       * @access public 
  86       * @param  array $conf 数据库连接信息 
  87       * @return  object     本类的单例对象 
  88       */ 
  89      public static function getDb($conf) 
  90      { 
  91          if(false === (static::$instance instanceof static)){ 
  92              static::$instance = new static($conf); 
  93          } 
  94          return static::$instance; 
  95      } 
  96      /** 
  97       * 禁止克隆 
  98       */ 
  99      public function __clone()
  100      {
  101      
  102      }
  103      /**
  104       * 关闭数据库连接
  105       * @access public
  106       */
  107      public function closeDb()
  108      {
  109          mysql_close($this->link);
  110      }
  111 
  112      public function exec($sql)
  113      {
  114          $result = $this->query($sql);
  115          return $this->affectedRows();
  116 
  117      }
  118      /**
  119       * 受影响的行数
  120       * @return int 返回受影响的行数
  121       */
  122      private function affectedRows()
  123      {
  124          return mysql_affected_rows($this->link);
  125      }
  126 
  127      /**
  128       * 执行 “返回一行数据”的查询
  129       * @param  string $sql sql语句
  130       * @return array      一维数组(一行)
  131       */
  132      public function getOneRow($sql)
  133      {
  134          $result = $this->query($sql);
  135          $data = mysql_fetch_assoc($result);
  136          mysql_free_result($result);
  137          return $data;
  138      }
  139      /**
  140       * 执行 "返回多行数据" 的查询
  141       * @param  string $sql sql语句
  142       * @return array      二维数组
  143       */
  144      public function getAllRows($sql)
  145      {
  146          $result = $this->query($sql);
  147          $data = array();
  148          while($row = mysql_fetch_assoc($result)){
  149              $data[] = $row;
  150          }
  151          mysql_free_result($result);
  152          return $data;
  153      }
  154      /**
  155       * 执行“获取一个数据”的查询
  156       * @param  string $sql sql语句
  157       * @return mixed      标量数据值
  158       */
  159      public function getOneData($sql)
  160      {
  161          $result = $this->query($sql);
  162          $data = mysql_fetch_row($result);
  163          mysql_free_result($result);
  164          return $data[0];
  165      }
  166 
  167      /**
  168       * 上次insert时的自增长id值
  169       * @return int insert时的id值
  170       */
  171      public function getInsertId()
  172      {
  173          return mysql_insert_id($this->link);
  174      }
  175 
  176      /**
  177       * 序列化时,对指定数据进行序列化
  178       * @return array 指定进行序列化的数据
  179       */
  180      public function __sleep()
  181      {
  182          return array(&#39;host&#39;, &#39;port&#39;, &#39;user&#39;, &#39;pass&#39;,&#39;charset&#39;, &#39;dbname&#39;);
  183      }
  184      /**
  185       * 反序列化时,使用相应数据连接数据库
  186       */
  187      public function __wakeup()
  188      {
  189          $this->connect(); //连接数据库
  190      }
  191      /**
  192     * 自动生成insert语句或update语句
  193     * @param array      $data          insert或update的数据
  194     * @param  string     $table        操作的数据表
  195     * @param  string     $act           是update还是insert操作
  196     * @param  string     $where      where条件 如 id=2  如果是update必须加,否则不执行直接返回false
  197     * @return bool        执行insert与update的结果
  198     */
  199      public function autoExecute($data, $table, $act=&#39;insert&#39;, $where=&#39;&#39;)
  200      {
  201          if($act == &#39;insert&#39;) {
  202              $sql = "insert into ".$table."(";
  203              $sql .=implode(",", array_keys($data));
  204              $sql .= ") values (&#39;";
  205              $sql .= implode("&#39;,&#39;", array_values($data));
  206              $sql .= "&#39;)";
  207 
  208              $res = $this->exec($sql);
  209               return $this->getInsertId();
  210 
  211          } else if($act == &#39;update&#39;) {
  212              if(!$where) { return false; }
  213              $sql = &#39;update &#39;.$table.&#39; set &#39;;
  214              foreach ($data as $k => $v) {
  215                  $sql .= $k."=&#39;".$v."&#39;,";
  216              }
  217              $sql = substr($sql, 0, -1);
  218              $sql .= &#39; where &#39;.$where;
  219 
  220              return $this->exec($sql);
  221          } else {
  222              return false;
  223          }
  224 
  225      }
  226  }
ログイン後にコピー

クリックしてツール クラスを表示

パブリック モデル クラスとパブリック コントローラー クラスを作成する

1) パブリック モデル クラス [Frame/BaseModel.class.php] ] データベース操作ツールクラスインスタンスの取得

 1 <?php
 2  
 3 /** 
 4  * BaseModel.class.php 基础模型类 
 5  *     连接数据库 
 6  */ 
 7 class BaseModel 
 8 { 
 9     protected $db = null;
 10     /**
 11      * 构造方法: 实例化数据库类
 12      * @access public13      * @param array $config  数据库配置信息
 14      */
 15     function __construct(array $config=null)
 16     {
 17         $conf = array(
 18             &#39;host&#39;=>&#39;localhost&#39;,
 19             &#39;user&#39;=>&#39;root&#39;,
 20             &#39;pwd&#39;=>&#39;root&#39;,
 21             &#39;port&#39;=>&#39;3306&#39;,
 22             &#39;charset&#39;=>&#39;utf8&#39;,
 23             &#39;dbname&#39;=>&#39;web&#39;,
 24         );
 25         $conf = empty($config)? $conf : array_merge($conf,$config);
 26         $this->db = Db::getDb($conf);
 27     }
 28 }
ログイン後にコピー

2)パブリックコントロールコンテナクラス[Frame/BaseController]:

統一コーディング

プロンプトメッセージjump

 1 <?php 
 2 /** 
 3  * BaseController.class.php  公共控制器 
 4  * @author young 
 5  */ 
 6  
 7 class BaseController 
 8 { 
 9     /**
 10      * 统一编码utf8
 11      */
 12     public function __construct()
 13     {
 14         header("content-type:text/html;charset=utf-8");
 15         session_start();
 16     }
 17 
 18     /**
 19      * 跳转提示
 20      * @access public
 21      * @param  string  $msg  跳转提示信息
 22      * @param  string  $url  跳转的地址
 23      * @param  integer $time 等待时间 秒数
 24      */
 25     public function msg($msg=&#39;&#39;, $url=&#39;?&#39;, $time=3)
 26     {
 27         echo "<p><a href=&#39;$url&#39;>返回</a></p>页面将在{$time}秒之后跳转!!";
 28         header("refresh: $time; url=$url");
 29         exit("<p><span style=&#39;color:red&#39;>$msg</span></p>");
 30     }
 31 }
ログイン後にコピー

3) ツールクラス、基本モデル、基本コントローラクラスをエントリーファイルに導入します

##【index.php】

#

 1 <?php 
 2 /** 
 3  * 入口文件 
 4  */
 5 require_once &#39;Frame/Db.class.php&#39;; 
 6 require_once &#39;Frame/BaseModel.class.php&#39;; 
 7 require_once(&#39;Model/UserModel.class.php&#39;); 
 8 require_once &#39;Frame/BaseController.class.php&#39;; 
 9 require_once &#39;Controller/UserController.class.php&#39;;
 10 
 11 //实例化控制器
 12 $userCtr = new UserController();
 13 
 14 $a = !empty($_GET[&#39;a&#39;]) ? $_GET[&#39;a&#39;] : &#39;login&#39;;
 15 
 16 $userCtr -> $a();
ログイン後にコピー

#クリックしてエントリーファイルを表示します

# 4) ユーザーモデルクラスの最適化【Model/UserModel.class.php】

 1 <?php 
 2  
 3 /**
 4  * UserModel.class.php 
 5  *     用户模型类-操作表pbg_users 
 6  */ 
 7 class UserModel extends BaseModel 
 8 { 
 9     /**
 10      * 检验登录信息
 11      * @param  array $data 用户提交的登录信息
 12      * @return bool       true-校验成功 false-校验失败
 13      */
 14     public function checkLoginInfo($data)
 15     {
 16         $sql = "select id,username,pwd from pbg_users where username=&#39;{$data[&#39;username&#39;]}&#39;";
 17         $res = $this->db->getOneRow($sql);
 18         return $res[&#39;pwd&#39;] == md5($data[&#39;pwd&#39;]) ? : false;
 19     }
 20 }
ログイン後にコピー

5) ユーザーコントローラーのログイン操作、ジャンププロンプトの最適化

パブリックコントローラーメソッド msg() を使用

 1 。。。。。。。 
 2     /** 
 3      * 登录操作: 校验登录信息 
 4      */ 
 5     public function dlogin() 
 6     { 
 7         //接收登录信息 
 8         $data = array(); 
 9         $data[&#39;username&#39;] = trim($_POST[&#39;username&#39;]);
 10         $data[&#39;pwd&#39;] = trim($_POST[&#39;pwd&#39;]);
 11 
 12         //实例化模型,调用模型方法
 13         $model = new UserModel();
 14         $result = $model->checkLoginInfo($data);
 15         //跳转提示
 16         if($result){
 17             $this->msg(&#39;登录成功!&#39;, &#39;?a=index&#39;,3);
 18         } else {
 19             $this->msg(&#39;用户名或密码不正确!!&#39;);
 20         }
 21     }
ログイン後にコピー

マージ、保存、git へのプッシュ

1 $ git add -A
2 $ git commit -m "MVC结构,数据库操作类,基础模型类和基础控制器类制作"
3 $ git checkout master
4 $ git merge mvc-dbtools-base
5 $ git push origin master
ログイン後にコピー
概要: ディレクトリ構造の最適化、データベース操作クラスの作成、基本モデル クラスと基本コントローラー クラスの使用

次のステップ: シングルトンの実装モデル クラスでは、ディレクトリ構造のさらなる最適化、プラットフォームの差別化 (フロントエンド、バックエンドなど)

上記がこの記事の全内容です。皆様の学習に役立つことを願っています。その他の関連コンテンツについては、こちらをご覧ください。 、PHP 中国語 Web サイトに注意してください。

関連する推奨事項:

PHP ソース コード 5 についての簡単な説明: 配列 array の作成について

PHP についての簡単な説明ソースコード 1: 関数の爆発と内破

#

以上がシングルエントリ MVC 構造を実装するための PHP ソース コード メソッドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!