计算机网络/计算机科学与应用/系统/运维/开发

Tp5.0 控制器的基本操作

一、控制器定义

application/index/controller/Index.php


<?php 

namespace app\index\controller;


class Index

{

    public function index(){

         return 'index';

    }

}


访问:http://domain/index/index/index


输出:

return json_encode($data);


二、初始化操作和前置操作

方法名 _initialize

也可以使用前置操作 在控制器中定义一个beforeActionList数组

     public $beforeActionList = [

     '方法名(所有操作都会执行本方法)',

     '方法名(数组内的操作不执行本方法)'=>['except'=>'action1,action2'],

     '方法名(数组内的操作才执行)'=>['only'=>'action1,action2']

     ];


三、跳转和重定向

success 或 error 方法输出信息并跳转到指定链接


application/index/controller/user/Wallet.php


namespace app\index\controller\user;


class Wallet{

public function index(){

                    return ...

               }

}

访问http://domain/index/user/wallet/index即可


四、获取请求详情

 Request::instance() request()函数 控制器方法依赖注入


$request = Request::instance();

$request->module()

$request->controller

$request->action


五、获取输入数据

     $request = Request::instance();

     // 获取name

     $name = $request->param('name');

     // 获取所有请求数据(经过过滤)

     $all = $request->param();

     // 获取所有数据(不经过过滤)

     $all = $request->param(false);

     // 获取get

     $name = $request->get('name');

     // 获取所有get数据(经过过滤)

     $all = $request->get();

     // 获取所有get数据(不经过过滤)

     $all = $request->get(false);

     //其他类似


数据过滤方法

         Request::instance()->get('name','','htmlspecialchars,strip_tags'

     );


获取部分数据

Request::instance()->only(['id','name']);


排除部分数据

Request::instance()->except(['password']);//排除密码字段的输入


数据类型处理

     Request::instance()->param('name/s'); // 字符串型

     Request::instance()->param('age/d');  // 整数型

     Request::instance()->param('agree/b'); // 布尔型

     Request::instance()->param('percent/f'); // 浮点型

     Request::instance()->param('list/a'); // 数组


参数绑定

将路由中匹配的变量作为控制器方法的参数传入即为参数绑定。


实例:

     http://localhost/index/news/show/id/10


控制器:

<?php 

namespace app\index\controller;


class News{

public function show($id){

                     echo '当前显示'.$id.'的新闻';

              }

}


页面缓存

实例:下列代码可使访问新闻详情时缓存10秒

     'post/:id' => ['index/post/show', ['cache' => 10]],


在浏览器中访问http://localhost/post/1时,会延迟10秒才更新界面,证明缓存生效


你努力了什么,也就成就了什么,与其羡慕别人,不如蜕变自己。

评论

^