最全的thinkphp5笔记整理

1.访问url

http://localhost:8080/tp5_book/public/index.php/模块名/控制器名/方法名

2.目录结构

├─application 应用目录(可设置)
│ ├─common 公共模块目录(可选)
│ ├─common.php 公共函数文件
│ ├─route.php 路由配置文件
│ ├─database.php 数据库配置文件
│ ├─config.php 应用配置文件
│ ├─module1 模块1目录
│ │ ├─config.php 模块配置文件
│ │ ├─common.php 模块函数文件
│ │ ├─controller 控制器目录
│ │ ├─model 模型目录(可选)
│ │ ├─view 视图目录(可选)

3.common文件夹的使用

在common文件夹下
	├─common
		├─controller
			├─Index.php
在Index.php中编写代码
		
别的模块调用
	index();
			}	
		}
	?>

4.更改应用配置

在根目录下创建文件
	├─conf
		├─config.php
	将app下的所有配置文件移到config.php下
定义配置文件目录
	├─public
		├─index.php
	// 定义配置文件目录目录
	define('CONF_PATH', __DIR__ . '/../conf/');
更改数据覆盖当前配置
	return [
		// 应用调试模式
		'app_debug'              => true,
		// 应用Trace
		'app_trace'              => false,
	];	
查看当前配置
	dump(config());
	注:显示的是thinkphp/convention.php下的所有配置信息

5.扩展配置

创建文件
	├─conf
		├─extra
在extra文件夹下创建扩展配置email.php
	'[email protected]',
			'name'=>'31321321',
		];
	?>
	输出的样式是
		["email"] => array(2) {
			["host"] => string(17) "[email protected]"
			["name"] => string(8) "31321321"
		}
	注意:扩展配置的优先级高于应用配置,及扩展配置会覆盖应用配置

6.场景配置

更改conf/config.php下的
	return[
		'app_status'=>'home'
	];
在conf下创建home.php和office.php场景配置文件
用法:
	如果'app_status'=>'home'则会调用home.php的配置文件
	如果'app_status'=>'office'则会调用office.php的配置文件
注意:
	在场景配置文件中必须配置对应栏目的所有项,否则配置会缺失(thinkphp5的bug)

7.模块配置

在conf文件夹下创建以模块名为命名的文件
	如:├─conf
		 ├─admin
		   ├─config.php
注:在conf/admin/config.php下的配置文件,只有在admin模块下生效
       在conf/admin中依然可以创建扩展配置文件夹extra,且只有在admin模块下生效

8.调用其他文件的方法

例:
在app下创建文件
	├─common
		├─Common.php
Common.php下编写方法
	
其他地方调用
(1)use app\common\Common;//显引用命名空间

	$result=new Common();
	$result->index();
	
(2)$result=new \app\common\Common;
    $result->index();

9.设置路由

在config.php更改配置
	// 是否开启路由
	'url_route_on'           => true,
	// 是否强制使用路由,开启时其他默认路由将被禁止
	'url_route_must'         => false,
新建文件
	├─conf
		├─route.php
在route.php文件下配置路由
	'index/index/demo1',
		    //带参数,访问:http://localhost:8080/tp5_test/public/index.php/demo2/2
		    'demo2/:id'			=>'index/index/demo2',
		];
	?>

10.请求对象request的使用

//获取当前域名
request()->domain()
//获取完整的url
request()->url()
//获取不包含get参数的url
request()->baseUrl()
//获取pathinfo,及获取当前的路径,含后缀
request()->pathinfo()
//获取当前的路径,不含后缀
request()->pathinfo()
//获取当前的请求类型
request()->method()
//判断请求类型
request()->isPost()		是post提交返回true
request()->isGet()		是get提交返回true
request()->isAjax()		是ajax方式提交返回true
//获取get参数
request()->get()		
//获取get参数和传给方法的参数值
request()->param()
//获取post参数
request()->post()
//获取会话控制的
request()->session()
request()->cookie()
//获取模块名 控制器名 操作方法
request()->module()
request()->controller()
request()->action()
注:获取某些指定的值
	request()->get('id')
	request()->session('username')

11.助手函数input的使用

//获取所有参数值
input()
//获取get参数
input('get.')
//获取post参数
input('post.')
//获取session
input('session.')
//获取cookie
input('cookie.')
//判断是否存在,如果get.id存在,返回true
input('?get.id')
注:
//获取具体的值
input('get.id')
//设置默认值,如果id不存在,返回100
input('get.id',100)
//设置强制转换
input('get.id',100,'intval')
//传递一些操作
input('get.id','','trim')	//去除字符串左右两边的空白符	

12.会话控制

session的使用
	配置文件
		'session'                => [
	        'id'             => '',
	        // SESSION_ID的提交变量,解决flash上传跨域
	        'var_session_id' => '',
	        // SESSION 前缀
	        'prefix'         => 'think',
	        // 驱动方式 支持redis memcache memcached
	        'type'           => '',
	        // 是否自动开启 SESSION
	        'auto_start'     => true,
		],
	赋值
		session('loginUsername', $data["username"], 'index');// 赋值index作用域
	获取
		session('loginUsername', '', 'index');// 赋值index作用域		
	判断是否存在
		session('?loginUsername', '', 'index');	返回1表示存在
	删除
		session(null,'index');

cookie的使用
	// 设置
	cookie('name', 'value', 3600);
	// 获取
	echo cookie('name');
	// 判断
	cookie('?name');返回1表示存在
	// 删除
	cookie('name', null);

13.调用视图view

调用对应视图,默认调用到‘view/控制器名/方法名.html’里的html文件
	return view();
调用指定视图
	return view('index/demo.php');
调用视图,并传参
	return view('index',['title'=>'主页面']);
	html页调用
		

{$title}

替换html指定内容 return view('','',['title'=>'替换内容']); 注:这会替换html里标签内外符合的内容,包括标签名、属性名

14.Controller方法的使用

	use think\Controller;//引用
	class Index extends Controller{//继承
		public function index(){
			(1)//另一种跳转方式,注:该方法的3个参数和view一样
				return $this->fetch();
			(2)//向前端页面传值
				$result="传值";
				$this->assign('res',$result);
				//前端接收
				{$res}
			(3)//直接输出一段字符串
				return $this->display('这是{$title}位置',['title'=>'标题']);
		}
	}

15.视图输出字符串内容替换

在config.php文件下配置
	//输出替换
    'view_replace_str'       => [
    	"__ADMIN__" =>'/tp5_book/public/static/admin',
    ],
	前台直接调用即可

16.{}的使用规则

{$data.name|md5}							>>>相当于>>>		
{$create_time|date="y-m-d",###}				>>>相当于>>>		
{$name|md5|strtoupper|substr=0,3}			>>>相当于>>>		
{:substr(strtoupper(md5($name)),0,3)}		>>>相当于>>>		
注:每个函数之间用丨符号隔开,且函数执行顺序是从右往左依次调用
       每个函数之间用:开头,且函数执行顺序是从左往右依次调用
原样输出{},禁止编译
	//在{literal}里的内容会被原样输出
	{literal}
		{$title}
	{/literal}
带参数的url
	{:url('goods/detail',array('id'=>$vo.id))}

17.视图循环

for循环
	{for start="1" end="10" step="2" name="k"}
		循环内容{$k}
	{/for}
	注:默认name="i",step="1"
	
foreach循环
	{foreach $user as $vo}
	    
	        {$vo.id}    
	    
    {/foreach}

18.视图判断循环

if语句
	{if condition="($vo.state==0) OR ($vo.state==1)"} 
	等待提现			
	{elseif condition="($vo.state==2)"/}
	成功
	{else /} 
	失败
	{/if}

19.视图页面引用公共html

在view下新建一个public文件,保存公共html文档
	{include file="public/_head"}
	{include file="public/_left"}

20.分页查询

控制器方法
	public function index(){
		$result=db('user')
				->order('time Desc')//排序,asc:升序排列,desc:降序排列
				->paginate(2);//分页
		$this->assign('user',$result);//将信息分配到前端模板
		return view();
	}
视图调用
	{foreach $user as $vo}
	    
	        {$vo.id}    
	    
    {/foreach}
    
    	{$user->render()} //分页
    

21.数据库助手函数操作

添加
	db('user')->insert($data);
更新
	db('store_wait')->update($data);
查询
	$result=db('store_wait')->select();	//多条
	$result=db('store_wait')->find();	//单条
指定字段查询
	$rows = db('store')
	        ->where('id',1)
	    	->field(['id','username'])//要查的字段
	    	->select();
关联查询
	$rows = db('store')
	    	->alias('s')//别名
	    	->join('goods g','s.id=g.store_id','left')//查询关联的信息与左表(及s表)不相关的信息
	    	->join('user u','s.user_id=u.id')
	        ->where('s.id',1)//条件
	    	->field(['s.*','g.*','u.username'])//要查的字段
	    	->select();
排序查询
	$result=db('user')->order('time Desc')->select();//排序,asc:升序排列,desc:降序排列
单条件查询
	$result=db('store_wait')->where('id',$id)->find();
多条件查询
	$result=db('store_wait')->where('goods_id='.$id.' and state=4')->find();
	$result=db('store_wait')->where('id',$id)->where('state',4)->find();
模糊查询
	$result=db('store_wait')->where('id','>',$id)->find();
	$result=db('store_wait')->where('id','like',$id.'%')->find();
计算总价
	$result=db('cart')->where('user_id',$user_id)->sum('cash');
	• max() 	表示查询某个字段的最大值
	• min()		表示查询某个字段的最小值
	• avg()		表示查询某个字段的平均值
	• sum()		表示求出某个字段的总和
	• count()	表示求出某个字段的查询数量
删除
	// 根据主键删除
	db('user')->delete(1);
	// 条件删除
	db('user')->where('id',1)->delete();

22.数据库原生操作

use think\Db;//导入Db类
$res1=Db::query("select * from tb_user where id=1");							//查询返回数据结果
$res2=Db::execute("update tb_user set username='2' where id=1");				//更新,成功返回更新的条数

23.验证器的使用

创建文件
	|——admin
		|——validate
			|——User.php
写入验证规则
	 'require|max:20|unique:user|min:10|confirm:password|captcha',		
		];
		protected $message = [
			'username.require' => '用户名不能为空',
			'username.max' => '用户名不能超过20位',
			'username.unique' => '用户名已存在',
			'username.min' => '用户名不能少于10位',
			'username.confirm' => '与密码不一致',
			'username.captcha'=>'验证码错误',
		];
		//场景验证
		protected $scene = [
			'edit' => ['phone','email','catch','time'],
			'add' => ['username'],
		];
	}
	?>
调用
	$validate=validate('User');
	if(!$validate->scene('add')->check($data)){
		$this->error($validate->getError());
	}

24.登录验证

创建文件
	|——admin
		|——controller
			|——Common.php
写入
	checklogin();
		}
		public function checklogin(){
			if(session('?loginUsername', '', 'admin')!=1){
				$this->error("你没有权限,请先登录","login/index");
			}
		}	
	}
	?>
调用
	控制器直接继承即可
	class Index extends Common{}

25.跳转方式

$this->success("添加成功!","user/index");
$this->error("添加失败!");
$this->redirect('catelist','',2,'纯跳转');

26.验证码

创建captcha.php设置验证码配置文件
	|——conf
		|——extra
			|——captcha.php
调用
	(1)
{:captcha_img()}
(2)
captcha

27.时间戳操作

// 需要先引入头文件
	use think\helper\Time;
// 获得今天的零点时间戳和23点59分59秒的时间戳
	list($start, $end) = Time::today();

其他的可以查看开发文档的时间戳操作 最全的thinkphp5笔记整理_第1张图片

28.返回json数据

return json(['data'=>$data,'code'=>1,'message'=>'操作完成']);

如果您觉得本篇内容不错,可以点个关注,给个赞

你可能感兴趣的:(php学习笔记)