Home  >  Article  >  php教程  >  ThinkPHP3.1的Widget新用法

ThinkPHP3.1的Widget新用法

WBOY
WBOYOriginal
2016-06-13 09:30:27719browse

ThinkPHP3.0版本的Widget对Action和View的支持力度是相对不够的,仅能够实现基本的模板渲染输出。而3.1版本的发布带来的多层MVC功能,给我们实现Widget的方式带来了新的思路,且看是如何实现吧。

由于ThinkPHP3.1增加了对多层MVC的支持,因此3.1版本可以支持多层的控制器功能,由此我们就可以在控制器层再增加一层:Widget层。

首先,还是在项目的Lib目录下面创建一个Widget目录,并且创建一个TestWidget类(Lib/Widget/TestWidget.class.php)如下:

class TestWidget extends Action{
  public function hello($name=''){
    echo ("hello,".$name."!");
  }
 }

我们看到TestWidget和之前的区别是没有继承Widget类,而是直接继承了Action类,这就代表着在TestWidget中可以直接调用Action的方法,包括对模板的渲染输出。

定义完成后,我们怎么调用这个Widget呢?用W方法肯定行不通了,这次需要R方法出场了。
R方法的作用是远程调用模块的操作,但是3.1赋予了它新的作用,可以支持调用所有控制器层的操作方法,所以,我们可以在模板中这样来调用Widget:

{:R('Test/hello',array('ThinkPHP'),'Widget')}

就可以实现在页面中的某个区域输出:

hello,ThinkPHP!

由于除了Action控制器之外的其他控制器层是无法直接通过URL访问的,所以这个Widget方法只能通过R方法在内部调用才可以。

你可以在TestWidget类中调用Model来输出其他数据,如果需要渲染自身的模板,则可以直接调用display方法就行了。

class TestWidget extends Action{
  public function hello($name=''){
    $this->assign('name',$name);
    $this->display('Test:hello');
  }
 }

我们在项目的Tpl/Test/ 目录下面创建一个hello(Tpl/Test/hello.html)模板文件,添加输出:

Hello,{$name}!

如果你希望和之前的Widget一样,把模板文件放到当前目录下面,则可以使用:

class TestWidget extends Action{
  public function hello($name=''){
    $this->assign('name',$name);
    $this->display(dirname(__FILE__).'/Test/hello.html');
  }
 }

这个时候,你就可以把刚才定义的hello模板文件放入Widget/Test/ 目录下面了。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn