PHP经验分享

《Thinkphp5入门系列课程》第六课:Controller学

2017-09-11  本文已影响1864人  6aec4f6b9d46

Thinkphp5视频教程

通过本文你可以学会:

开始 Controller

下面是 thinkphp5 安装后默认的 application/index/controller/index.php :

<?php
namespace app\index\controller;

class Index
{
    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a href="http://www.qiniu.com" target="qiniu">七牛云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_bd568ce7058a1091"></thinkad>';
    }
}

首先从路径分析,applicationthinkphp5 应用的主目录,项目所有的业务代码基本都存放在这里,当然如果你不喜欢 application 这个名字,比如说改成 app 也是可以的,这个后面我们讲配置的时候再说。紧接着 index 目录是模块 index 业务代码存放的目录,如果熟悉 thinkphp3.2 的同学应该知道,这是 tp 框架的典型应用:分模块。每个模块下面都有自己独立的业务代码如:controller,model 等。所以,controller 目录下面存放就是 index 模块所需要的 controller 文件咯。

通过命令行创建 controller

thinkphp5 为我们提供了方便的命令行工具 php think,它为我们提供了一键创建 controller, model, migration 的功能。

这里我们在 index 模块下面创建一个 DemoController 控制器:

php think make:controller index/Demo

创建的控制器如下:

<?php

namespace app\index\controller;

use think\Controller;
use think\Request;

class Demo extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}

默认 thinkphp 为我们自动填充了一些常用的方法,是不是很方便 ^ - ^.

controller 数据输出

thinkphp5 开始数据都是自动输出的,不需要我们手动的指定数据格式输出,例如,我们需要输出一段文字,可以这样:

public function index ()
{
    return 'hello world';
}

直接 return 就可以啦。如果我们想输出数组的话,可以这样:

首先在 application/config.php 文件中将 default_return_type 的值改为 json,然后我们就可以在方法里面这样:

public function index()
{
    return [
        'name' => 'xiaoteng',
    ];
}

建议:数组定义尽量使用上面这种短语法格式。

controller 的跳转及应用

thinkphp5 为我们提供了四种跳转的方法,有大家知道的 success(), error(), redirect(), 还有一个官方文档没有说明的 result() 方法,下面就详细的给大家介绍下这几种方法。

四种方法的结构

方法名 参数 作用
success() success($msg = '', $url = null, $data = '', $wait = 3, array $header = []) 如果你需要在用户交互操作中间增加一个显示操作状态的页面,那么就可以使用这个方法
error() error($msg = '', $url = null, $data = '', $wait = 3, array $header = []) 同上
redirect() redirect($url, $params = [], $code = 302, $with = []) 直接重定向到指定的 URL
result() result($data, $code = 0, $msg = '', $type = '', array $header = []) 适用于 API 接口的数据返回,默认帮你封装了 code, msg, time, data 四个字段,详细内容见下面内容
参数名 必选 说明
$msg 说明文本
$url 需要跳转的 url 地址
$data 需要附加的数据
$wait 跳转等待时间
$header 是否增加额外的头信息
参数名 必选 说明
$url 重定向的地址
$params URL需要附加的参数
$code 重定向发送的 HTTP 状态码,一般都为302不需要修改
$with 隐式传参,将 with 里面的数据保存到 session 中,注意该值只在第一次访问有效
参数名 必选 说明
$data 需要附加的数据
$code API接口状态码,这里一般都是开发团队内部约定
$msg 说明文本
$type 返回的数据格式,可以是 jsonxml
$header 是否增加额外的头信息

result() 方法返回的 json 数据结构:

{
  "code": 200,
  "msg": "获取用户信息成功",
  "time": 1505097522,
  "data": {
    "id": 1,
    "name": "xiaoteng"
  }
}

result() 方法返回的 xml 数据结构:

<think>
  <code>200</code>
  <msg>获取用户信息成功</msg>
  <time>1505098107</time>
  <data>
    <id>1</id>
    <name>xiaoteng</name>
  </data>
</think>

success()error() 的跳转页面自定义

它们默认的跳转页面是这样的:

success 和 error 的默认跳转页面

我们并不想使用默认的样式,想改成下面这样:

自定义跳转页面

这里的页面只做演示,所以就很简陋。我不会告诉你我css很烂的。

可以这样做:

application/common/view 目录下创建 jump.html 文件,内容如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>跳转提示</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        * { font-family: "Microsoft Yahei" }
        .success { color: green; }
        .error { color: red; }
        .text-center { text-align: center; }
    </style>
  </head>
  <body>

    <div class="container">
        <div class="row">
            <div class="col-lg-12 <?php echo $code==1?'success':'error' ?>">
                <h3 class="text-center"><?php echo(strip_tags($msg));?></h3>
            </div>
            <div class="col-lg-12">
                <p class="jump text-center">
                    页面自动 <a id="href" href="<?php echo($url);?>">跳转</a> 等待时间: <b id="wait"><?php echo($wait);?></b>
                </p>
            </div>  
        </div>
    </div>

    <script type="text/javascript">
        (function(){
            var wait = document.getElementById('wait'),
                href = document.getElementById('href').href;
            var interval = setInterval(function(){
                var time = --wait.innerHTML;
                if(time <= 0) {
                    location.href = href;
                    clearInterval(interval);
                };
            }, 1000);
        })();
    </script>
  </body>
</html>
<?php
return [
    'dispatch_success_tmpl' => APP_PATH . '/common/view/jump.html',
    'dispatch_error_tmpl' => APP_PATH . '/common/view/jump.html',
];

第二步将我们第一步创建的文件绑定到跳转的配置参数中。

Q:为什么不直接修改 application/config.php 文件呢?
A:考虑到不同模块使用的跳转页面可能不同。

好咯,到这里 successerror 的跳转页面更换成我们自定义的啦。我们来看看效果:

新的跳转页面

教程就到这里啦。此篇是小滕的《Thinkphp5入门系列课程》第六课:Contorller 学习(一)。喜欢的给个订阅呗!

由于作者水平有限,如有错误请欢迎指正。

上一篇 下一篇

猜你喜欢

热点阅读