ThinkPhp初学笔记
PHP、Apache搭建完成以后安装ThinkPhp框架
WEB是Apache网站目录,应用根目录为tp;在WAMP目录下按照tp,也可正常启动。
以上为默认单应用模式。
composer require topthink/think-multi-app
注意:安装的时候一定要是在项目的根目录下安装,需要删除app目录下的Controller,如果没有安装think-multi-app或安装时目录选择错误, 使用php think build xx会报错:Command "build" is not defined.
ThinPhp MVC:
链接:https://zhuanlan.zhihu.com/p/275910257
新版框架默认只能支持PHP原生模板,如果需要使用thinkTemplate模板引擎,需要安装think-view扩展(该扩展会自动安装think-template依赖库)
composer require topthink/think-view

视图目录可以在根目录,也可以在app应用目录,可以通过config目录下的view.php修改视图配置
要使用View,必须先引入 think\facade\View
门面类
模板渲染的最典型用法是直接使用fetch
方法,不带任何参数,系统会按照默认规则自动定位视图(view)目录下的模板文件,其规则是:控制器名(小写+下划线)/操作名(方法名字).html
controller代码
<?php namespace app\controller; use think\facade\View; class Index{ public function index(){ return View::fetch(); } }
view代码(注:在app目录下,view目录需要我们手动创建)
注意:控制器里面类对应view
下面的目录
注意:控制器里面方法对应view
下面的目录里的静态文件
使用assign
方法进行全局模板变量赋值
模版输出 {$name}
controller代码
namespace app\controller; use think\facade\View; class Index{ public function index(){ // 模板变量赋值 View::assign('name','xx'); View::assign('qq','。。。'); // 或者批量赋值 View::assign([ 'name' => 'xx', 'qq' => '。。。' ]); // 模板输出 return View::fetch(); } }
view代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ThinkPHP6</title> </head> <body> 姓名:{$name} <br> QQ:{$qq} </body> </html>
assign
方法赋值属于全局变量赋值,如果你需要单次赋值的话,可以直接在fetch
方法中传入
controller代码
namespace app\controller; use think\facade\View; class Index{ public function index(){ // 模板输出并变量赋值 return View::fetch('index', [ 'name' => 'xx', 'qq' => '..' ]); } }
thinkphp6 模板常量配置 静态资源路径配置及使用
view.php 配置添加:
'tpl_replace_string' =>array( '{__STATIC__}'=>'/static', '{__CSS__}'=>'/static/css', '{__JS__}'=>'/static/js', '{__IMG__}'=>'/static/img' )
html 文件中引入静态资源