This article mainly introduces the new usage of ThinkPHP3.1 widgets. For more information, see the ThinkPHP3.0 Widget's support for Action and View, only basic template rendering outputs can be implemented. The multi-layer MVC feature introduced by the release of version 3.1 brings us new ideas for implementing widgets, and how to implement it.
Because ThinkPHP3.1 has added support for multi-layer MVC, version 3.1 can support multi-layer controller functions, so we can add another layer on the controller layer: Widget layer.
First, create a Widget Directory under the Lib Directory of the project and create a 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 the Widget class, but directly inherits the Action class, which means that the Action method can be directly called in TestWidget, including rendering and output of the template.
How can we call this Widget after the definition is complete? The W method certainly won't work. this time, the R method is required.
The role of the R method is to remotely call the operations of the module, but 3.1 gives it a new role and supports calling the operation methods at all controller layers. therefore, we can call the Widget in the template as follows:
{:R('Test/hello',array('ThinkPHP'),'Widget')}
You can achieve output in a certain area of the page:
hello,ThinkPHP!
Since other controller layers except the Action Controller cannot be accessed directly through URLs, 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 directly call the display method.
class TestWidget extends Action{ public function hello($name=''){ $this->assign('name',$name); $this->display('Test:hello'); } }
In the Tpl/Test/directory of the project, create a hello (Tpl/Test/hello.html) template file and add the output:
Hello,{$name}!
If you want to put the template file under the current directory like the previous Widget, you can use:
class TestWidget extends Action{ public function hello($name=''){ $this->assign('name',$name); $this->display(dirname(__FILE__).'/Test/hello.html'); } }
At this time, you can put the defined hello template file under the Widget/Test/directory.