動態網站的簡單搭建(基於ThinkPHP5)


靜態部分

新建項目文件夾

找到wampserver的www網站運行的根目錄

新建項目文件夾,命名為Myproject(起一個自己喜歡的名字,純英文或拼音)

打開PHPStorm

找到剛剛創建的文件夾並打開

引入ThinkPHP開發框架

ThinkPHP5開源框架

配置Apache目錄映射文件

找到"httpd-vhosts.conf"文件

配置一個虛擬主機

復制代碼到文件末尾

MyProject -> 自己的項目文件名稱

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "C:/wamp64/www/MyProject/public"
  <Directory "C:/wamp64/www/MyProject/public/>
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>

重啟wampserver

等待重啟

打開瀏覽器,輸入localhost

項目初始化

打開PHPstorm,打開目錄:MyProject->application->index

創建view(視圖)文件夾 MyProject->application->index->New->Directory->view

創建model(模型)文件夾 MyProject->application->index->New->Directory->model

創建視圖模板(html)文件主目錄 MyProject->application->index->view->New->Directory->index

創建視圖模板(html)主頁文件 MyProject->application->index->view->index->New->HTML File

創建完成(index.html)

創建項目靜態資源文件夾 MyProject->public->static

創建樣式表(CSS)文件夾 MyProject->public->static->New->Directory->CSS

創建圖片(Images)文件夾 MyProject->public->static->New->Directory->Images

創建JS(JavaScript)文件夾 MyProject->public->static->New->Directory->JavaScript

添加靜態資源文件

新建CSS文件(style.css) MyProject->public->static->CSS->New->Stylesheet->style.css

新建js文件(index.js) MyProject->public->static->JavaScript->New->JavaScript File->index.js

添加一張圖片

編寫index.html文件 MyProject->application->index->view->index->index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="./static/css/style.css">
    <title>主頁</title>
</head>
<body>
<div class="main">
    <h1>MyProject</h1>
</div>
</body>
<script src="./static/JavaScript/index.js"></script>
</html>

編寫style.css文件 MyProject->public->static->CSS->style.css

body{
    background-image: repeating-linear-gradient(100deg, #afe191, #ed8e89);
}
.main{
    width: 80%;
    height: 3rem;
    margin-left: 10%;
    margin-top: 10%;
    border-radius: 10px;
    box-shadow: 1px 1px 20px #000000;
    text-align: center;
}
h1{
    color: #FFFFFF;
    font-size: 30px;
}

編寫index.js文件 MyProject->public->static->JavaScript->index.js

alert("項目初始化成功!");

編寫主控制器文件(index.php) MyProject->application->index->controller->index.php

<?php
namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
    public function index()
    {
        return $this->fetch('index/index');
    }
}

准備完畢,打開瀏覽器輸入localhost進入到主界面

至此,靜態部分網站已全部完成

動態部分

調整ThinkPHP框架的配置信息 MyProject->application->config.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

return [
    // +----------------------------------------------------------------------
    // | 應用設置
    // +----------------------------------------------------------------------

    // 應用調試模式
    'app_debug'              => true,
    // 應用Trace
    'app_trace'              => false,
    // 應用模式狀態
    'app_status'             => '',
    // 是否支持多模塊
    'app_multi_module'       => true,
    // 入口自動綁定模塊
    'auto_bind_module'       => false,
    // 注冊的根命名空間
    'root_namespace'         => [],
    // 擴展函數文件
    'extra_file_list'        => [THINK_PATH . 'helper' . EXT],
    // 默認輸出類型
    'default_return_type'    => 'html',
    // 默認AJAX 數據返回格式,可選json xml ...
    'default_ajax_return'    => 'json',
    // 默認JSONP格式返回的處理方法
    'default_jsonp_handler'  => 'jsonpReturn',
    // 默認JSONP處理方法
    'var_jsonp_handler'      => 'callback',
    // 默認時區
    'default_timezone'       => 'PRC',
    // 是否開啟多語言
    'lang_switch_on'         => false,
    // 默認全局過濾方法 用逗號分隔多個
    'default_filter'         => '',
    // 默認語言
    'default_lang'           => 'zh-cn',
    // 應用類庫后綴
    'class_suffix'           => false,
    // 控制器類后綴
    'controller_suffix'      => false,

    // +----------------------------------------------------------------------
    // | 模塊設置
    // +----------------------------------------------------------------------

    // 默認模塊名
    'default_module'         => 'index',
    // 禁止訪問模塊
    'deny_module_list'       => ['common'],
    // 默認控制器名
    'default_controller'     => 'Index',
    // 默認操作名
    'default_action'         => 'index',
    // 默認驗證器
    'default_validate'       => '',
    // 默認的空控制器名
    'empty_controller'       => 'Error',
    // 操作方法后綴
    'action_suffix'          => '',
    // 自動搜索控制器
    'controller_auto_search' => false,

    // +----------------------------------------------------------------------
    // | URL設置
    // +----------------------------------------------------------------------

    // PATHINFO變量名 用於兼容模式
    'var_pathinfo'           => 's',
    // 兼容PATH_INFO獲取
    'pathinfo_fetch'         => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
    // pathinfo分隔符
    'pathinfo_depr'          => '/',
    // URL偽靜態后綴
    'url_html_suffix'        => 'html',
    // URL普通方式參數 用於自動生成
    'url_common_param'       => false,
    // URL參數方式 0 按名稱成對解析 1 按順序解析
    'url_param_type'         => 0,
    // 是否開啟路由
    'url_route_on'           => true,
    // 路由使用完整匹配
    'route_complete_match'   => false,
    // 路由配置文件(支持配置多個)
    'route_config_file'      => ['route'],
    // 是否開啟路由解析緩存
    'route_check_cache'      => false,
    // 是否強制使用路由
    'url_route_must'         => false,
    // 域名部署
    'url_domain_deploy'      => false,
    // 域名根,如thinkphp.cn
    'url_domain_root'        => '',
    // 是否自動轉換URL中的控制器和操作名
    'url_convert'            => true,
    // 默認的訪問控制器層
    'url_controller_layer'   => 'controller',
    // 表單請求類型偽裝變量
    'var_method'             => '_method',
    // 表單ajax偽裝變量
    'var_ajax'               => '_ajax',
    // 表單pjax偽裝變量
    'var_pjax'               => '_pjax',
    // 是否開啟請求緩存 true自動緩存 支持設置請求緩存規則
    'request_cache'          => false,
    // 請求緩存有效期
    'request_cache_expire'   => null,
    // 全局請求緩存排除規則
    'request_cache_except'   => [],

    // +----------------------------------------------------------------------
    // | 模板設置
    // +----------------------------------------------------------------------

    'template'               => [
        // 模板引擎類型 支持 php think 支持擴展
        'type'         => 'Think',
        // 默認模板渲染規則 1 解析為小寫+下划線 2 全部轉換小寫
        'auto_rule'    => 1,
        // 模板路徑
        'view_path'    => '',
        // 模板后綴
        'view_suffix'  => 'html',
        // 模板文件名分隔符
        'view_depr'    => DS,
        // 模板引擎普通標簽開始標記
        'tpl_begin'    => '{',
        // 模板引擎普通標簽結束標記
        'tpl_end'      => '}',
        // 標簽庫標簽開始標記
        'taglib_begin' => '{',
        // 標簽庫標簽結束標記
        'taglib_end'   => '}',
    ],

    // 視圖輸出字符串內容替換
    'view_replace_str'       => [],
    // 默認跳轉頁面對應的模板文件
    'dispatch_success_tmpl'  => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
    'dispatch_error_tmpl'    => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',

    // +----------------------------------------------------------------------
    // | 異常及錯誤設置
    // +----------------------------------------------------------------------

    // 異常頁面的模板文件
    'exception_tmpl'         => THINK_PATH . 'tpl' . DS . 'think_exception.tpl',

    // 錯誤顯示信息,非調試模式有效
    'error_message'          => '頁面錯誤!請稍后再試~',
    // 顯示錯誤信息
    'show_error_msg'         => false,
    // 異常處理handle類 留空使用 \think\exception\Handle
    'exception_handle'       => '',

    // +----------------------------------------------------------------------
    // | 日志設置
    // +----------------------------------------------------------------------

    'log'                    => [
        // 日志記錄方式,內置 file socket 支持擴展
        'type'  => 'File',
        // 日志保存目錄
        'path'  => LOG_PATH,
        // 日志記錄級別
        'level' => [],
    ],

    // +----------------------------------------------------------------------
    // | Trace設置 開啟 app_trace 后 有效
    // +----------------------------------------------------------------------
    'trace'                  => [
        // 內置Html Console 支持擴展
        'type' => 'Html',
    ],

    // +----------------------------------------------------------------------
    // | 緩存設置
    // +----------------------------------------------------------------------

    'cache'                  => [
        // 驅動方式
        'type'   => 'File',
        // 緩存保存目錄
        'path'   => CACHE_PATH,
        // 緩存前綴
        'prefix' => '',
        // 緩存有效期 0表示永久緩存
        'expire' => 0,
    ],

    // +----------------------------------------------------------------------
    // | 會話設置
    // +----------------------------------------------------------------------

    'session'                => [
        'id'             => '',
        // SESSION_ID的提交變量,解決flash上傳跨域
        'var_session_id' => '',
        // SESSION 前綴
        'prefix'         => 'think',
        // 驅動方式 支持redis memcache memcached
        'type'           => '',
        // 是否自動開啟 SESSION
        'auto_start'     => true,
    ],

    // +----------------------------------------------------------------------
    // | Cookie設置
    // +----------------------------------------------------------------------
    'cookie'                 => [
        // cookie 名稱前綴
        'prefix'    => '',
        // cookie 保存時間
        'expire'    => 0,
        // cookie 保存路徑
        'path'      => '/',
        // cookie 有效域名
        'domain'    => '',
        //  cookie 啟用安全傳輸
        'secure'    => false,
        // httponly設置
        'httponly'  => '',
        // 是否使用 setcookie
        'setcookie' => true,
    ],

    //分頁配置
    'paginate'               => [
        'type'      => 'bootstrap',
        'var_page'  => 'page',
        'list_rows' => 15,
    ],
];

利用PHPMyAdmin新建數據庫

初始賬號為:root

初始密碼為:空

新建MyProject數據庫 (測試用表,可自行更改)

新建shop表 (測試用表,可自行更改)

向shop表中添加部分數據

調整數據庫配置信息 MyProject->application->database.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

return [
    // 數據庫類型
    'type'            => 'mysql',
    // 服務器地址
    'hostname'        => '127.0.0.1',
    // 數據庫名
    'database'        => 'MyProject',
    // 用戶名
    'username'        => 'root',
    // 密碼
    'password'        => '',
    // 端口
    'hostport'        => '3308',
    // 連接dsn
    'dsn'             => '',
    // 數據庫連接參數
    'params'          => [],
    // 數據庫編碼默認采用utf8
    'charset'         => 'utf8',
    // 數據庫表前綴
    'prefix'          => 'MyProject_',
    // 數據庫調試模式
    'debug'           => true,
    // 數據庫部署方式:0 集中式(單一服務器),1 分布式(主從服務器)
    'deploy'          => 0,
    // 數據庫讀寫是否分離 主從式有效
    'rw_separate'     => false,
    // 讀寫分離后 主服務器數量
    'master_num'      => 1,
    // 指定從服務器序號
    'slave_no'        => '',
    // 自動讀取主庫數據
    'read_master'     => false,
    // 是否嚴格檢查字段是否存在
    'fields_strict'   => true,
    // 數據集返回類型
    'resultset_type'  => 'array',
    // 自動寫入時間戳字段
    'auto_timestamp'  => false,
    // 時間字段取出后的默認時間格式
    'datetime_format' => 'Y-m-d H:i:s',
    // 是否需要進行SQL性能分析
    'sql_explain'     => true,
];

添加數據模型 MyProject->application->index->model->New->PHP Class->Shop

使數據模型繼承Model

<?php

namespace app\index\model;

use think\Model;

class Shop extends Model
{

}

重構項目

引入前端框架LayUI

LayUi v2.5.6

官網

導入到目錄 MyProject->public->static

重寫主頁模板文件 MyProject->application->index->view->index->index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="./static/layui/css/layui.css">
    <link rel="stylesheet" href="./static/css/style.css">
    <title>主頁</title>
</head>
<body>
<div class="main">
    <h1>MyProject</h1>
</div>
<div class="crud">
    <div id="add" class="crud-main">
       添加
    </div>
    <div id="del" class="crud-main">
        刪除
    </div>
    <div id="alter" class="crud-main">
        修改
    </div>
</div>
<div class="list">
    <div class="head"> 商品列表 </div>
    <div class="list-body">
        <table>
            <tr class="tol">
                <td>ID</td>
                <td>名稱</td>
                <td>價格</td>
                <td>日期</td>
            </tr>
            {foreach $data as $item}
                <tr>
                    <td>{$item['id']}</td>
                    <td>{$item['name']}</td>
                    <td>${$item['price']}</td>
                    <td>{$item['time']}</td>
                </tr>
            {/foreach}
        </table>
    </div>
</div>
</body>
<script src="./static/layui/layui.js"></script>
<script src="./static/JavaScript/index.js"></script>
</html>

重寫CSS靜態資源文件 MyProject->public->static->CSS->style.css

body{
    background-image: repeating-linear-gradient(100deg, #afe191, #ed8e89);
}
.main{
    width: 80%;
    height: 3rem;
    margin-left: 10%;
    margin-top: 8%;
    border-radius: 10px;
    background-color: #1a1e33;
    line-height: 3rem;
    box-shadow: 1px 1px 20px #000000;
    text-align: center;
}
.crud{
    width: 35%;
    height: 25rem;
    background-color: #00000005;
    margin-left: 10%;
    margin-top: 2rem;
    box-shadow: 1px 1px 10px #00000010;
    padding: 2rem 2rem;
}
.crud-main{
    transition: all 0.2s linear;
    width: 8rem;
    height: 8rem;
    border-radius: 5px;
    box-shadow: 1px 1px 10px #000000;
    text-align: center;
    font-size: 30px;
    font-weight: bolder;
    line-height: 7rem;
}
.crud-main:hover{
    transition: all 0.3s linear;
    box-shadow: 1px 1px 20px #000000;
    cursor: pointer;
}
.list{
    width: 35%;
    height: 25rem;
    background-color: #00000005;
    margin-left: 51%;
    margin-top: -29rem;
    position: relative;
    box-shadow: 1px 1px 10px #00000010;
    padding: 2rem 2rem;
}
.list .head{
    width: 80%;
    height: 2rem;
    position: relative;
    left: 10%;
    background-color: #00000090;
    font-weight: bolder;
    color: #FFFFFF;
    font-size: 20px;
    text-align: center;
    box-shadow: 1px 1px 5px #000000;
    line-height: 2rem;
}
.list .list-body{
    width: 100%;
    height: 90%;
    position: relative;
    top: 1.5rem;
}
.list-body table{
    width: 100%;
}
table td{
    height: 2rem;
    text-align: center;
    background-color: rgba(255, 255, 255, 0.19);
    font-size: 15px;
    font-weight: bolder;
    color: #000000;
}
.tol td{
    background-color: rgba(101, 15, 19, 0.56);
    font-size: 18px;
    font-weight: bolder;
    color: #ffffff;
}
#add{
    background-color: #8aebb6;
    color: #000000;
}
#del{
    background-color: #000000;
    color: #ffffff;
    margin-left: 11rem;
}
#alter{
    background-color: #ff8053;
    color: #ffffff;
    margin-left: 22rem;
}
h1{
    color: #FFFFFF;
    font-size: 30px;
}

重寫JavaScript文件 MyProject->public->JavaScript->index.js

僅演示 增加 刪、改、查只需類比即可

layui.use(['jquery','layer'],function () {
    $ = layui.jquery;
    layer = layui.layer;
    
    // 添加
    $("#add").on("click",function () {
        var name='';
        var price=0;
        layer.prompt({
            title:'請輸入商品名稱',
            formType: 2,
        },function (n) {
            name = n;
            layer.prompt({
                title:'請輸入商品價格',
                formType: 3,
            },function (p) {
                price = p;
                var datas = {
                    'n':name,
                    'p':price
                };
                layer.closeAll();
                $.post({
                    url:'/add',
                    data:datas,
                    success:function () {
                        layer.alert("OK!",function () {
                            location.href = '/';
                        });
                    }
                });
            });
        });
    });
    // 刪除
    $("#del").on("click",function () {

    });
    // 修改
    $("#alter").on("click",function () {

    });
});

重寫主控制器 MyProject->application->index->controller->index.php

<?php
namespace app\index\controller;

use think\Controller;
use think\Db;

class Index extends Controller
{
    public function index()
    {
        $data = Db::name('shop')
            ->select();
        $this->assign('data',$data);
        return $this->fetch('index/index');
    }
}

配置數據路由 MyProject->application->route.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

use think\Route;
Route::post('add/','index/Index/add');

return [
    '__pattern__' => [
        'name' => '\w+',
    ],
    '[hello]'     => [
        ':id'   => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
        ':name' => ['index/hello', ['method' => 'post']],
    ],

];

重構后主頁效果

添加

添加成功

至此動態部分結束

簡單那動態網站的搭建全部結束,如需拓展記得BaiDu~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM