本文实例讲述了从thinkphp3.2.3过渡到thinkphp5.0学习笔记。分享给大家供大家参考,具体如下:

用tp3.2.3做了不少项目,但是毕竟要与时代接轨,学习一些新的框架,比如tp5

以下记录一些学习中遇到的问题及解决办法,还有tp3.2和tp5.0的一些区别,适合给用过tp3没用过tp5的童鞋做个参考。

随着学习不断更新……

+++++++++++++++++++++++分割线总是要有的+++++++++++++++++++++++

首先到下载了一个最新的thinkphp5.0.22完整版:

直接扔到了服务器上,解压后目录结构如下:

目录结构整体与tp3.2大同小异,文件夹首字母小写了,应用入口文件 在根目录下 public/index.php,官方文档对public文件夹定义为web部署目录(对外访问目录):

配置服务器域名解析的时候需要把项目根目录指向/public:

<virtualhost *:80>
 serveradmin 1977629361@qq.com
 documentroot /var/www/tp/public
 servername tp.oyhdo.com
 serveralias tp.oyhdo.com
 directoryindex index.php index.html index.htm 
</virtualhost>

根目录下 application/config.php 为应用(公共)配置文件,设置一些常用的配置,以下简称为“配置文件”:

访问网址如下:

访问tp.oyhdo.com等同于访问tp.oyhdo.com/index.php/index/index/index(默认不区分大小写)

即默认模块index,默认控制器index,默认操作index

配置文件修改分别为default_moduledefault_controllerdefault_action

如果需要强制区分url大小写,修改 url_convert false

配置文件中设置 app_debug true,打开应用调试模式,以便开发调试:

【隐藏url中的index.php入口文件】

以apache服务器为例,首先确认apache配置文件httpd.conf中开启了mod_rewrite.so模块:

然后把所有【allowoverride】设为all:

 最后修改根目录下 public/.htaccess 文件内容为:

<ifmodule mod_rewrite.c>
 options +followsymlinks -multiviews
 rewriteengine on
 rewritecond %{request_filename} !-d
 rewritecond %{request_filename} !-f
 rewriterule ^(.*)$ index.php?/$1 [qsa,pt,l]
</ifmodule>

去掉
index.php也可访问:

【隐藏前台url模块名】 

把index模块作为前台,在前台新建了一个user控制器:

<?php
namespace app\index\controller;

class user
{
 public function user()
 {
 return '这是user控制器的user操作';
 }
}

 正常需要这样访问user控制器的user操作:

 为了前台url显示简洁一些,要去掉模块名index,然后就崩了:

如果只有一个模块,可以在 /application/common.php 中添加:

// 绑定当前访问到index模块
define('bind_module','index');

亲测访问成功:

但是项目通常会有前后台的区分,至少两个模块, 用上面的方法绑定index模块后,再访问其它模块就会报错:

(新建了一个admin模块作为后台)

<?php
namespace app\admin\controller;

class index
{
 public function index()
 {
 return '这是后台首页';
 }
}

 

对于多模块的情况,可以在 /application/route.php 中绑定默认模块路由(去掉上面的单模块绑定):

use think\route;
route::bind('index');

前台访问成功:

 然后在/public/下新建一个入口文件admin.php,绑定后台模块admin,来访问后台:

<?php
// [ 应用入口文件 ]
namespace think;
// 定义应用目录
define('app_path', __dir__ . '/../application/');
// 加载框架引导文件
require __dir__ . '/../thinkphp/base.php';
// 绑定当前入口文件到admin模块
route::bind('admin');
// 关闭admin模块的路由
app::route(false);
// 执行应用
app::run()->send();

后台访问成功:

(修改后台地址只需修改这个文件名即可)
 

【返回数据】

配置文件中默认输出类型 default_return_type 为html:

 直接打印输出字符串、数组,没什么特殊:

public function index()
{
 $str = 'hello,world!';
 $arr = array('state'=>1,'msg'=>'success');

 //打印字符串
 echo $str;

 //打印数组
 var_dump($arr);
}

返回json格式数据:

public function index()
{
 $arr = array('state'=>1,'msg'=>'success');
 return json($arr);
 
 //返回其它状态码或响应头信息
 //return json($arr, 201, ['cache-control' => 'no-cache,must-revalidate']);

 //xml格式
 //return xml($arr);
}

(对于只做api开发的情况,可以设置default_return_type为json,直接return $arr即可返回json格式数据)
 

【渲染模板、分配数据】

如图建立视图层,index.html作为前台首页(内容为“这是首页”):

tp3渲染模板直接在控制器里$this->display(),tp5并不支持。

tp5渲染模板,在控制器中继承think\controller类,使用 return $this->fetch() 或者使用助手函数 return view()

<?php
namespace app\index\controller;
use think\controller;
class index extends controller
{
 public function index()
 {
 return $this->fetch();
 //return view();
 }
}

tp5分配数据的方式依旧使用 $this->assign()

<?php
namespace app\index\controller;
use think\controller;
class index extends controller
{
 public function index()
 {
 	$name = 'lws';
 $this->assign('name',$name);
 return $this->fetch();
 }
}

index.html页面读取数据:

{$name}

(修改模板引擎标签 配置文件【tpl_begin】、【tpl_end】)

【继承父类控制器】

写一个栗子,新建一个base控制器作为父类控制器,index控制器继承base控制器

在父类控制器中初始化分配数据,子类控制器渲染模板:

base.php:

<?php
namespace app\index\controller;
use think\controller;
class base extends controller
{ 
 //初始化方法
 public function _initialize()
 {	
 	$haha = '快下班了';
 $this->assign('haha',$haha);
 }
}

index.php:

<?php
namespace app\index\controller;
use think\controller;
class index extends base
{
 public function index()
 {
 return $this->fetch();
 }
}

index.html:

{$haha}

(与tp3.2相比,父类控制器不能是public控制器) 

【配置参数】

tp3.2里面使用c方法设置、获取配置参数

tp5使用助手函数 config() 设置、获取配置参数:

//配置一个参数
config('name','lws');

//批量配置参数
config([
 'info'=>['sex'=>'nan','aihao'=>'nv']
]);

//获取一个配置参数
echo config('name');

//获取一组配置参数
dump(config('info'));

//获取一个二级配置参数
echo config('info.sex');

【get传参】

tp5废除了url/参数名1/参数值1/参数名2/参数值2……这样的方式传参,还是老老实实用url?参数名1=参数值1&参数名2=参数值2……这样传吧。

控制器里打印$_get

<?php
namespace app\index\controller;
use think\controller;
class index extends controller
{
 public function index()
 {
 $getdate = $_get;
 dump($getdate);	
 }
}

 这样是不对滴:

这样就好使:

【安全获取变量】 

tp3.2可以使用i方法安全获取get、post等系统输入变量

tp5中使用助手函数 input()

//获取get变量
$data1 = input('get.name');

//获取post变量
$data2 = input('post.name');

//获取当前请求变量
$data3 = input('param.name');

//获取request变量
$data4 = input('request.name');

//获取cookie变量
$data5 = input('cookie.name');

//获取session变量
$data6 = input('session.name');

//获取上传文件信息
$data7 = input('file.image');

(注意:获取的数据为数组,要加上 /a 修饰符才能获取到)

$arr = input('post.arr/a');

可以在配置文件中设置全局过滤方法:

// 默认全局过滤方法 用逗号分隔多个
'default_filter'  => 'htmlspecialchars',

【数据库操作】

tp5的数据库配置文件在根目录 /application/database.php:(也可在模块下单独配置)

连接数据库:tp3.2支持m方法连接数据库,tp5使用 db类 或 助手函数db()

查询数据:依旧使用 find()select() 方法,查询一个字段使用 value() 方法代替getfield()

//查询一条
$artinfo = db('article')->find();

//查询全部
$artinfo = db('article')->select();

//查询一个字段
$artinfo = db('article')->value('article_title');

添加数据:tp3.2使用add(),tp5使用 insert():返回插入条数  或  save():返回id

//添加一条数据
$data['article_title'] = 'php是世界上最好的语言';
$data['article_content'] = '如题';
db('article')->insert($data);
//或 db('article')->save($data);
//添加多条数据
$data = [
 ['article_title' => '标题1', 'article_content' => '内容1'],
 ['article_title' => '标题2', 'article_content' => '内容2'],
 ['article_title' => '标题3', 'article_content' => '内容3']
];
db('article')->insertall($data);

修改数据:tp3.2使用save(),tp5使用 update()

//修改数据
$whe['article_id'] = 1;
$data['article_title'] = '修改后的标题';
db('article')->where($whe)->update($data);

删除数据:没错还是 delete()

//删除数据
$whe['article_id'] = 1;
db('article')->where($whe)->delete();

db()助手使用起来比较方便,但每次都会重新连接数据库,因此应当尽量避免多次调用,建议还是使用db类操作数据库。

db类操作原生sql:

<?php
namespace app\index\controller;
use think\db;
class index {
 public function index() {
 // 插入记录
 $res = db::execute('insert into lws_article (title ,content) values ("标题", "内容")');
	
 // 删除数据
 $res = db::execute('delete from lws_article where art_id = 1 ');

 // 更新记录
 $res = db::execute('update lws_article set title = "修改标题" where art_id = 1 ');

 // 查询数据
 $res = db::query('select * from lws_article where art_id = 1');

 // 显示数据库列表
 $res = db::query('show tables from blog');

 // 清空数据表
 $res = db::execute('truncate table lws_article');
 }
}

db类操作查询构造器:

<?php
namespace app\index\controller;
use think\db;
class index {
 public function index() {
	// 查询数据(数据库没有配置表前缀)
	$res = db::table('lws_article')
	 ->where('art_id', 1)
	 ->select();

	//以下为数据库配置了表前缀	

	// 插入记录
	$res = db::name('article')
		->insert(['title' => '标题', 'content' => '内容']);

	// 更新记录
	$res = db::name('article')
		->where('art_id', 1)
		->update(['title' => "修改标题"]);

	// 查询数据
	$res = db::name('article')
		->where('art_id', 1)
		->select();

	// 删除数据
	$res = db::name('article')
		->where('art_id', 1)
		->delete();
 
 //链式操作举例
 $artlist = db::name('article')
	 ->where('is_del', 'n')
	 ->field('id,title,content')
	 ->order('post_time', 'desc')
	 ->limit(10)
	 ->select();
 } 
}

【切换数据库】

首先在数据库配置中配置多个数据库:

// 数据库配置1
'db1' => [
	// 数据库类型
	'type' => 'mysql',
	// 服务器地址
	'hostname' => '127.0.0.1',
	// 数据库名
	'database' => 'blog1',
	// 数据库用户名
	'username' => 'root',
	// 数据库密码
	'password' => '123456',
	// 数据库连接端口
	'hostport' => '',
	// 数据库连接参数
	'params' => [],
	// 数据库编码默认采用utf8
	'charset' => 'utf8',
	// 数据库表前缀
	'prefix' => 'lws_',
],
// 数据库配置2
'db2' => [
	// 数据库类型
	'type' => 'mysql',
	// 服务器地址
	'hostname' => '127.0.0.1',
	// 数据库名
	'database' => 'blog2',
	// 数据库用户名
	'username' => 'root',
	// 数据库密码
	'password' => '',
	// 数据库连接端口
	'hostport' => '',
	// 数据库连接参数
	'params' => [],
	// 数据库编码默认采用utf8
	'charset' => 'utf8',
	// 数据库表前缀
	'prefix' => 'lws_',
],

使用connect方法切换数据库:

<?php
namespace app\index\controller;
use think\db;
class index {
 public function index() {
 $db1 = db::connect('db1');
 $db2 = db::connect('db2');
 $db1->query('select * from lws_article where art_id = 1');
 $db2->query('select * from lws_article where art_id = 2');
 }
}

【系统常量】

tp5废除了一大堆常量:

request_method is_get 
is_post  is_put 
is_delete is_ajax 
__ext__  common_module 
module_name controller_name 
action_name app_namespace 
app_debug module_path等

需要使用的常量可以自己定义,例如is_get、is_post

我在父类的初始化方法中定义了这两个常量:

<?php
namespace app\index\controller;
use think\controller;
class base extends controller
{
 public function _initialize()
 {	
 	define('is_get',request()->isget());
 define('is_post',request()->ispost());
 }
}

然后在子类控制器中就可以使用这个常量做一些判断:

<?php
namespace app\index\controller;
class index extends base
{
 public function index()
 { 
 if(is_post){
  echo 111;
 }else{
  echo 222;
 }
 }
}

【定义路由】

例如一篇博客详情页,原来的网址为:http://oyhdo.com/home/article/detial?id=50,即home模块下的article控制器下的detial操作方法,传递参数id。

在路由配置文件 application/route.php 中添加路由规则:

return [
 'article/:id' => 'home/article/detial',
];

或者使用 route 类,效果一样: 

use think\route;
route::rule('article/:id','home/article/detial');

定义路由规则之后访问http://oyhdo.com/article/50即可

 【url分隔符的修改】

修改 application/config.php 中的 pathinfo_depr :

// pathinfo分隔符
 'pathinfo_depr'  => '-',

访问网址变为:http://oyhdo.com/article-50

【跳转、重定向】

tp3里面的正确跳转:$this->success()、错误跳转:$this->error()、重定向:$this->redirect(),在tp5里面同样适用(继承\think\controller

tp5新增 redirect() 助手函数用于重定向:

return redirect('https://www.oyhdo.com');

更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》及《php模板技术总结》。

希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。