ThinkPhp5入门

TP5的前置操作.md

2018-01-10  本文已影响0人  傲娇的泰迪

1、什么是前置操作?

构造方法可以看作类中所有方法的前置操作,而前置操作更强大,不仅可以把某个方法指定为全部方法的前置操作,还能指定为特定方法的前置操作,或者除了某个方法之外所有方法的前置操作。

2、为什么必须继承基类Controller,才能创建前置操作?

Controller.php中有protexted $beforeActionList = [];(即:前置操作列表)

3、前置操作有什么用?如何正确的使用它?

打开默认控制器index.php,内容:

<?php
namespace app\index\controller
class Index extends \think\Controller
{
  protected $beforeActionList=[ //前置方法列表,继承自Controller
    'before1'=>'', //为空,表示before1是当前类中全部操作的前置操作
    'before2'=>['only'=>'demo2'], //before2仅对demo2操作有效
    'before3'=>['except'=>'demo1, demo2'],
  ]; //before3仅对除了demo1,demo2之外的操作有效
  protected $siteName; //自定义属性
  protected function before1()
  {
    $this->siteName = $this->request->param('name');
  }
  protected function before2()
  {
    $this->siteName = '坚决抵制萨德';
  }
  protected function before3()
  {
    $this->siteName = '此生无悔入MC';
  }
  public function demo1()
  {
    return $this->siteName; 
  }
  public function demo2()
  {
    return $this->siteName; 
  }
  public function demo3()
  {
    return $this->siteName; 
  }
}
?>

在url中的写法如下:

tp5/com/index/index/demo1/name/我爱php //输出我爱php
tp5/com/index/index/demo2/name/我爱php //输出坚决抵制萨德,因为before2重写了siteName为坚决抵制萨德
tp5/com/index/index/demo3/name/我爱php //输出此生无悔入MC,因为before3重写了siteName为此生无悔入MC

在之前的版本中,除了前置操作,还有后置操作,不过在ThinkPHP5中,已经取消了形同鸡肋的后置操作。

上一篇下一篇

猜你喜欢

热点阅读