【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");
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
ThinkPHP6 中使用 ElasticSearch 需要先安装 ElasticSearch 和 Elasticsearch for PHP,具体安装步骤请参考前面的回答。 安装完成后,我们可以在代码中使用 Elasticsearch for PHP 提供的 API 进行数据的增删改查操作。下面是一个简单的示例: ```php <?php namespace app\controller; use Elasticsearch\ClientBuilder; use think\facade\Db; class Index { public function search() { $client = ClientBuilder::create()->build(); $params = [ 'index' => 'my_index', 'body' => [ 'query' => [ 'match' => [ 'title' => 'ElasticSearch' ] ] ] ]; $response = $client->search($params); return json($response); } public function add() { $data = Db::table('my_table')->find(); $client = ClientBuilder::create()->build(); $params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => $data['id'], 'body' => [ 'title' => $data['title'], 'content' => $data['content'], ] ]; $response = $client->index($params); return json($response); } public function update() { $client = ClientBuilder::create()->build(); $params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'doc' => [ 'title' => 'new title', ] ] ]; $response = $client->update($params); return json($response); } public function delete() { $client = ClientBuilder::create()->build(); $params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id' ]; $response = $client->delete($params); return json($response); } } ``` 这里我们定义了四个方法,分别是 `search`、`add`、`update` 和 `delete`。 `search` 方法用于查询数据,我们在查询中使用了 `match` 查询,查询了 `title` 字段中包含 `ElasticSearch` 关键字的文档。 `add` 方法用于添加数据,我们使用了 `index` 方法,将 `my_table` 表中的数据添加到了名为 `my_index`,类型为 `my_type` 的文档中。 `update` 方法用于更新数据,我们使用了 `update` 方法,将 ID 为 `my_id` 的文档中的 `title` 字段更新为了 `new title`。 `delete` 方法用于删除数据,我们使用了 `delete` 方法,删除了 ID 为 `my_id` 的文档。 这只是一个简单的示例,实际使用中需要根据业务需求进行更详细的配置和操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coleak

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值