我正在深入学习Yii2,所以我想知道一个小部件是否有可能在控制器中有类似于动作的东西?
例如:
class WTest extends Widget {
public ...;
public function init() {
...
}
public function run() {
Pjax::begin();
echo "<a href='".Yii::$app->urlManager->createAbsoluteUrl("test/add")."'>Add test</a>";
Pjax::end();
}
public function addThing() {
echo "hola"
}
}
然后在控制器中执行:
class TestController extends Controller
{
public function actionAdd() {
$wObj = new WTest;
return $wObj->addThing();
}
}
这种方式的问题是我在表单中调用窗口小部件时松开了所有参数集,因为我称之为“新WTest”,它是一个新实例.我也试过使用静态方法,但类似的问题,任何想法?
UPDATE
在视图中,我正在调用这个小部件:
WTest::widget([
'test' => 'hi'
]);
解决方法:
更新:删除私有__contruct(),__ clone()并使用yii2依赖注入.
在类WTest中,您应该定义一些函数和变量:
class WTest extends Widget
{
/**
* @var WTest The reference to *WTest* instance of this class
*/
private static $instance;
/**
* Returns *WTest* instance of this class.
*
* @return WTest The *WTest* instance.
*/
public static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static();
//Add more attribute and do many stuff here
}
return static::$instance;
}
//If you want set value for variable, use yii2 DI
/** @var string $test */
public $test;
}
并在你的行动中使用:
public function actionAdd() {
$wObj = WTest::getInstance();
return $wObj->addThing();
}
在视图中使用:
WTest::widget([
'test' => 'value',
]);
希望它有用.
有关更多信息singleton pattern:http://www.vincehuston.org/dp/singleton.html.
祝好运并玩得开心点!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。