本文目录导读:
ThinkPHP 是一款优秀的 PHP 框架,以其简洁、高效和强大的功能而著称,本篇将详细介绍如何使用 ThinkPHP 3.2 来构建一个完整的企业网站,我们将从安装到部署,再到具体功能的实现,逐步展开讲解。
安装与配置
安装环境准备
首先确保您的服务器满足以下条件:
图片来源于网络,如有侵权联系删除
- 操作系统:Windows/Linux/MacOS
- PHP 版本:5.6 或更高版本
- MySQL 数据库(可选)
- Web 服务器:Apache/Nginx/IIS 等
下载最新版本的 ThinkPHP 3.2 并解压至本地目录。
wget http://www.thinkphp.cn/ThinkPHP_3.2.zip unzip ThinkPHP_3.2.zip
将 ThinkPHP_3.2
文件夹移动到您的主机根目录下。
mv ThinkPHP_3.2 /var/www/html/
在浏览器中访问 http://localhost/index.php
,如果显示欢迎页面则说明安装成功。
配置数据库连接
打开 application/config/database.php
文件,进行如下设置:
return array( 'type' => 'mysql', // 数据库类型 'hostname' => '127.0.0.1', // 主机名 'database' => 'testdb', // 数据库名称 'username' => 'root', // 用户名 'password' => '', // 密码 'port' => '3306', // 端口 );
保存文件后,运行命令生成数据表结构:
cd application php think db:generate
基本控制器与视图
创建第一个控制器 IndexController
和对应的视图 index.html
。
创建控制器
在 application/controllers
目录下新建文件夹 Index
,并在其中创建 IndexController.class.php
文件:
<?php class IndexController extends Controller { public function index() { $this->assign('title', 'Welcome to Our Company'); $this->display(); } } ?>
创建视图
在 application/views
目录下创建 index.html
文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php echo $title; ?></title> </head> <body> <h1>Welcome to <?php echo $title; ?>!</h1> <p>这是我们的首页。</p> </body> </html>
路由与URL重写
通过修改 application/config/routes.php
文件来定义路由规则:
图片来源于网络,如有侵权联系删除
return array( '/^index\/$/' => 'Index:index', );
这样,当访问 /index
时,会自动跳转到 IndexController
的 index()
方法。
为了启用 URL 重写,需要在 Apache 中添加以下配置:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php/$1 [QSA,L]
重启 Apache 后即可生效。
模型与数据操作
创建模型
在 application/models
目录下创建 ArticleModel.class.php
文件:
<?php class ArticleModel extends Model { protected $_auto = array( array('create_time','time',1,'function'), ); } ?>
控制器中的数据操作
在 IndexController
中增加文章列表展示功能:
public function articleList() { $articles = D('Article')->select(); $this->assign('articles',$articles); $this->display('article_list'); } public function addArticle() { if(IS_POST){ $data = I('post.'); if(D('Article')->add($data)){ $this->success('添加成功',U('/index/articleList')); }else{ $this->error('添加失败'); } }else{ $this->display('add_article'); } }
对应视图文件 application/views/article_list.html
和 application/views/add_article.html
分别用于展示文章列表和添加文章界面。
权限控制与管理员后台
权限控制
在 application/libraries/Auth.class.php
中定义角色和权限:
class Auth { private static $auth; public static function instance(){ if(!self::$auth instanceof self){ self::$auth = new self(); } return self::$auth;
标签: #thinkphp3.2 企业网站源码
评论列表