【Thinkphp 6】框架基础知识

简介: 【Thinkphp 6】框架基础知识

环境搭建

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
composer create-project topthink/think tp
php think run

框架基础规则

继承引入

use app\BaseController;
class coleak extends BaseController

use进行引入,然后继承基础的方法

单应用模式

入口文件(index.php)可以省略

http://localhost:8000/coleak/test
http://localhost:8000/index.php/coleak/test

多应用模式

composer require topthink/think-multi-app

在app里新建文件夹,并将相应的控制器(controller)放到新建的文件夹下

遵守类名和文件名一致,空间名和文件夹名一致

namespace app\cc\controller;
http://localhost:8000/cc/coleak/test

自定义路由

http://localhost:8000/coleak/hello/a

调试器

重命名为 .env

public function c()
    {
        $arr=['id'=>1,"name"=>"coleak"];
        $name='coleak';
//        return "666".'21a1';
//        return json($arr);
//        dump($arr);
//        dump($name);
//        halt终止程序并输出dunp
//        halt($arr);
//        halt($name);
//
//        trace调试器中输出
        trace($arr);
        trace($name);
//        dump($ar);
    }

空控制器

在controller下面定义个Error.php

<?php
namespace app\cc\controller;
class Error{
    public function __call($name, $arguments)
    {
        // TODO: Implement __call() method.
        return "Error Requests!";
    }
}

视图

模板引擎安装

composer require topthink/think-view

看下composer.json

"require": {
        "php": ">=7.2.5",
        "topthink/framework": "^6.1.0",
        "topthink/think-orm": "^2.0",
        "topthink/think-filesystem": "^1.0",
        "topthink/think-multi-app": "^1.0",
        "topthink/think-view": "^1.0"
    },

渲染模板

public function t()
    {
        return view(1);
    }
//如果html文件名和方法名一致,即为t.html。则无需参数
    public function t()
    {
        return view();
    }

facade代理

use think\facade\View;
    public function t()
    {
//        return view();
        return View::fetch();
    }
//或者直接使用(不推荐)
return \think\facade\View::fetch();

当方法使用驼峰命名法是,如testColeak,则对应的html文件应该为test_coleak

变量传递

view.php

'tpl_begin'     => '{',
    // 模板引擎普通标签结束标记
    'tpl_end'       => '}',
    // 标签库标签开始标记
    'taglib_begin'  => '{',
    // 标签库标签结束标记
    'taglib_end'    => '}',

语法

public function testColeak(){
        View::assign("name","coleak");
        View::assign("age",19);
        return View::fetch();
    }
{$name}
{$age}

查看编译后的文件

在runtime/cc/temp

发现进行了一个htmlentities处理,不让html标签解析,进行原样显示

让其解析则加一个|raw

{$name}
<br>
{$name|raw}
View::assign("name","<h1>coleak</h1>");
<?php echo htmlentities($name); ?>
<br>
<?php echo $name; ?>

默认值

{$a|default="coleak"}

数组按键取值

$arr=["name"=>"coleak","age"=>19];
View::assign("arr",$arr);
{$arr["name"]}-{$arr.age}

md5加密

{$arr["name"]|md5}-{:md5($arr.name)}

请求

request信息

//http://127.0.0.1:8000/cc/c/test  
public function test()
    {
//        dump(Request::method());
        dump($this->request->method());
        dump($this->request->ip());
        dump($this->request->host());
        dump($this->request->scheme());
        dump($this->request->url());
        dump($this->request->root());
        dump($this->request->baseUrl());
    }
^ "GET"
^ "127.0.0.1"
^ "127.0.0.1:8000"
^ "http"
^ "/cc/c/test"
^ "/cc"
^ "/cc/c/test"

参数接收

//http://127.0.0.1:8000/cc/c/server/b/2?a=45
    public function server()
    {
        dump($this->request->get());
        //pathinfo传参
//      /参数名1/参数值1/参数名2/参数值2...
        dump($this->request->route());
        //通用的
        dump($this->request->param());
    }

^ array:1 [▼

“a” => “45”

]

^ array:1 [▼

“b” => “2”

]

^ array:2 [▼

“a” => “45”

“b” => “2”

]

生成URL

public function url()
    {
        echo Route::buildUrl();
        echo "<br>";
        echo Route::buildUrl("coleak/testColeak",["name"=>"coleak","age"=>19]);
        echo "<br>";
        echo Route::buildUrl("coleak/testColeak",["name"=>"coleak","age"=>19])
        ->domain("www.baidu.com")
        ->suffix("phtml");
        echo "<br>";
        echo url("coleak/testColeak",["name"=>"coleak","age"=>19]);
    }
/cc/C/url.html
/cc/coleak/testColeak.html?name=coleak&age=19
http://www.baidu.com/cc/coleak/testColeak.phtml?name=coleak&age=19
/cc/coleak/testColeak.html?name=coleak&age=19

文件上传

上传及验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="" enctype="multipart/form-data" method="post">
    file:<input type="file" name="image">
    <br>
    <button>提交</button>
<!--    <input type="submit" value="upload">-->
</form>
</body>
</html>
<?php
namespace app\cc\controller;
use app\BaseController;
use think\facade\View;
use think\facade\Filesystem;
class Upload extends BaseController{
    public function upload(){
        if ($this->request->isPost())
        {
//            $file=$this->request->file("image");
//            dump($file);
            $file=$this->request->file();
            dump($file);
            $size=1000*1024;
            validate(["image"=>"image|fileSize:{$size}|fileExt:jpg"])
            ->check($file);
            $savefile=Filesystem::disk("public")->putfile("uploads",$file["image"]);
            dump($savefile);
            echo "successed";
        }else{
            return View::fetch();
        }
    }
}

验证功能

验证器

<?php
namespace app\validate;
use think\Validate;
class Student extends Validate{
    protected $rule=[
        'name'=>"require|chs|length:2,15",
        "age"=>'require|number|between:18,60'
    ];
    protected $message=[
      'name.require'=>"姓名为空",
        'age.require'=>"年龄为空",
        'name.chs'=>"姓名不为汉字",
        'name.length'=>"姓名长度错误",
        'age.number'=>"年龄不为数字",
        'age.between'=>"年龄不符合范围",
    ];
}
public function add(){
        $arr1=["name"=>"coleakxiao","age"=>19];
        $arr2=["name"=>"小1","age"=>19];
        $arr3=["name"=>"小","age"=>11];
        $arr4=["name"=>"小小小","age"=>22];
        $stu=new Student();
//        if(!$stu->check($arr1))
//        {
//            echo $stu->getError().PHP_EOL;
//        }
//        if(!$stu->check($arr4))
//        {
//            echo $stu->getError().PHP_EOL;
//        }
//        echo "successed".PHP_EOL;
//        validate(Student::class)->check($arr4);
//        validate(Student::class)->check($arr1);//验证失败会抛出异常
        //匿名函数形式验证方式
        validate(
            ['name'=>"require|chs|length:2,15"],
            ['name.require'=>"姓名为空", 'name.chs'=>"姓名不为汉字", 'name.length'=>"姓名长度错误",]
        )->check($arr4);
//scene定义场景验证,function自定义接口验证
        try {
//            echo $aaa;
            validate(Student::class)->check($arr4);
            validate(Student::class)->check($arr1);
        }catch(ValidateException $e)
        {
            echo $e->getMessage();
        }
        catch (\Exception $e)//两次捕获不同的异常,验证异常放在普通的异常捕获前面
        {
            echo $e->getMessage();
        }
    }

表单令牌

public function form(){
        if($this->request->isPost() and $this->request->checkToken("__token__"))
        {
//            $r1=$this->request->checkToken("__token__");
//            dump($r1);
            //或者直接在验证器里面设置 'name'=>"require|chs|length:2,15|token:__token__"
            dump($this->request->param());
        }
        else {
            return View::fetch();
        }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    <input type="hidden" name="__token__" value="{:token()}" />
  name:<input type="text" name="user">
    <br>
  <br>
  <button>提交</button>
</form>
</body>
</html>

中间件

php think make:middleware Check
middleware.php中修改
\app\middleware\Check::class
        public function handle($request, \Closure $next)
    {
        dump(111);
//        if ($request->param())
    return $next($request);
    }

杂项

session

开启session中间件 \think\middleware\SessionInit::class

class coleak extends BaseController
  {
    public function ss1(){
        Session::set("name","coleak");
        $arr=["name"=>"coleak1","age"=>19,"sex"=>"男"];
        Session::set("arr",$arr);
    }
    public function ss2()
    {
        dump(Session::get("arr"));
        Session::delete("name");
        dump(Session::has("name"));
        dump(Session::all());
        Session::clear();
        dump(Session::all());
    }

在config/session.php配置session相关的属性

Cookie

public function ss3()
    {
        Cookie::set("name","ayuexiao",3600);
        dump(Cookie::get("name"));
        Cookie::delete("name");
    }


目录
相关文章
|
13天前
|
缓存 安全 PHP
【PHP开发专栏】Symfony框架核心组件解析
【4月更文挑战第30天】本文介绍了Symfony框架,一个模块化且高性能的PHP框架,以其可扩展性和灵活性备受开发者青睐。文章分为三部分,首先概述了Symfony的历史、特点和版本。接着,详细解析了HttpFoundation(处理HTTP请求和响应)、Routing(映射HTTP请求到控制器)、DependencyInjection(管理依赖关系)、EventDispatcher(实现事件驱动编程)以及Security(处理安全和认证)等核心组件。
|
8月前
|
前端开发 关系型数据库 开发工具
构建自己的MVC框架(Ruby语言实现)-- 开篇
构建自己的MVC框架(Ruby语言实现)-- 开篇
|
SQL 前端开发 程序员
Laravel和Thinkphp有什么区别,哪个框架好用
Laravel和Thinkphp有什么区别,哪个框架好用
696 0
|
NoSQL JavaScript 中间件
知新 | koa框架入门到熟练第二章
这里对koa-bodyparser的使用教程。
540 0
|
开发框架 PHP 容器
codeigniter-3.1 PHP开发框架
环境需求 最低硬件配置:1核CPU,1G内存(1+1)提示:如果你的应用较多,而主机节点的硬件配置较低,建议在部署节点时开通虚拟虚拟内存; 生产环境建议使用2G或以上内存; 推荐安装系统:Ubuntu-16.
986 0
|
PHP 数据库
Thinkphp入门 五 —模型 (49)
原文:Thinkphp入门 五 —模型 (49) 【数据库操作model模型】 model  模型  数据库操作 tp框架主要设计模式:MVC C:controller   控制器   shop/Lib/Action/具体控制器 V:view       视图     shop/Tpl/分组...
977 0
|
SQL .NET 开发框架
ThinkPhp学习11
原文:ThinkPhp学习11 一、模板的使用        (重点)   a、规则    模板文件夹下[TPL]/[分组文件夹/][模板主题文件夹/]和模块名同名的文件夹[Index]/和方法名同名的文件[index].
739 0
|
PHP 数据安全/隐私保护 缓存
ThinkPhp学习13
原文:ThinkPhp学习13 简单登录验证 创建Login类 1 Login类对应的模板 1 2 3 用户名: 4 密 码: 5 验证码: //src=Code类下的code方法,Math.
833 0
|
PHP
ThinkPhp学习06
原文:ThinkPhp学习06 一、简单学习修改用户信息模块 1、编写UserAction.class.php 1 View Code  2、UserAction对应index方法的页面 1 2 3 4 5 Insert title here...
846 0
|
PHP .NET SQL
ThinkPhp学习12
原文:ThinkPhp学习12  二、输出模板内容      (重点)  a、display    1.display中没有参数    $this->display();    2.可以带参数    $this->display(本模块文件夹下的其他模板文件);    $this->displ...
894 0