动态网站的简单搭建(基于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{
     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 appindexcontroller;

use thinkController;

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类 留空使用 	hinkexceptionHandle
    '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 appindexmodel;

use thinkModel;

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{
     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{
     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;
     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{
     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{
     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{
     100%;
    height: 90%;
    position: relative;
    top: 1.5rem;
}
.list-body table{
     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 appindexcontroller;

use thinkController;
use thinkDb;

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 thinkRoute;
Route::post('add/','index/Index/add');

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

];

重构后主页效果

添加

添加成功

至此动态部分结束

简单那动态网站的搭建全部结束,如需拓展记得BaiDu~

原文地址:https://www.cnblogs.com/JQ04/p/13546473.html