2016-07-17 40 views
2

我正在深入学习Yii2的过程,所以我想知道是否有可能让一个小部件在控制器中有类似的操作?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(); 
    } 
} 

有这样的问题是,我失去调用形式widget时设置的所有参数,因为我我叫“新WTest”,这是一个新的例子。我也试过使用静态方法,但类似的问题,任何想法?

UPDATE 在视图中,我打电话小部件是这样的:

 WTest::widget([ 
      'test' => 'hi' 
     ]); 
+0

如果你想只有一个实例引导我正确的方向,你应该使用'singleton'模式吧。 – ThanhPV

+0

你能举个例子吗?我不知道如何申请单身人士在这种情况下 – Eduardo

回答

2

更新:删除private __contruct(), __clone()和使用yii2依赖注入。在意见

public function actionAdd() { 
    $wObj = WTest::getInstance(); 
    return $wObj->addThing(); 
} 

用途: 在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; 
} 

而在你的动作使用

WTest::widget([ 
    'test' => 'value', 
]); 

希望它有帮助。

有关单身模式的更多信息:http://www.vincehuston.org/dp/singleton.html

祝你好运,玩得开心!从ThanhPV

+0

非常感谢花时间。我会试试看:) – Eduardo

+0

看起来它不起作用:1.克隆和构建需要是超类的公共应有方法。 2.当我从视图中调用小部件时,我将它传递给参数,如何让它们保持使用Singleton? – Eduardo

+0

我更新我的答案,如果你想为变量注入价值,你不需要单身。 Yii2采用依赖注入设计。 – ThanhPV

0

答案是不是完全正确的,但它使用依赖注入:)