New Usage of Widget in ThinkPHP3.1

  • 2021-07-01 06:46:22
  • OfStack

ThinkPHP version 3.0 of Widget is relatively inadequate to support Action and View, and can only achieve basic template rendering output. The release of version 3.1 brings a multi-layer MVC function, which brings us a new idea to realize Widget. Let's see how to realize it.

Since ThinkPHP 3.1 adds support for multi-layer MVC, version 3.1 can support multi-layer controller functions, so we can add another layer to the controller layer: Widget layer.

First, create an Widget directory under the Lib directory of the project, and create an TestWidget class (Lib/Widget/TestWidget. class. php) as follows:


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

We can see that the difference between TestWidget and the previous one is that it does not inherit Widget class, but directly inherits Action class, which means that Action methods can be directly called in TestWidget, including rendering output of templates.

After the definition is completed, how do we call this Widget? The W method will definitely not work. This time, the R method is needed.
The R method is used to remotely invoke the operation of the module, but 3.1 gives it a new role, which can support calling all the operation methods of the controller layer, so we can call Widget in the template as follows:


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

You can output in a certain area of the page:


hello,ThinkPHP!

Because other controller layers other than the Action controller cannot be accessed directly through URL, this Widget method can only be called internally through the R method.

You can call Model in the TestWidget class to output other data. If you need to render your own template, you can call display method directly.


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

We create an hello (Tpl/Test/hello. html) template file under the project's Tpl/Test/ directory and add output:


Hello,{$name}!

If you want to put the template file under the current directory like the previous Widget1, you can use:


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

At this point, you can put the hello template file you just defined under the Widget/Test/directory.


Related articles: