ThinkPHP3.0 version of Widget has relatively insufficient support for Action and View, and can only achieve basic template rendering output. The multi-layer MVC function brought by the release of version 3.1 has brought new ideas to the way we implement Widgets. Let's see how to implement 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: the 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 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. This means that the Action method can be directly called in TestWidget, including the rendering output of the template.
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 function of the R method is to remotely call the operation of the module, but 3.1 has given it a new function, which can support calling the operation methods of all controller layers. Therefore, we can call the Widget in the template like this:
{:R('Test/hello',array('ThinkPHP'),'Widget')}
You can achieve output in a certain area on the page:
hello,ThinkPHP!
Since other controller layers except 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 just call the display method directly.
class TestWidget extends Action{ public function hello($name=''){ $this->assign('name',$name); $this->display('Test:hello'); } }
We create a hello (Tpl/Test/hello.html) template file under the Tpl/Test/ directory of the project and add output:
Hello,{$name}!
If you want to put the template file in 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 hello template file you just defined into the Widget/Test/ directory.