简体   繁体   English

Yii2。 小部件和操作

[英]Yii2. Widgets and Actions

I am in the process of learning Yii2 more in depth, so I was wondering if it is possible for a widget to have something similar to actions in a controller? 我正在深入学习Yii2,所以我想知道一个小部件是否有可能在控制器中有类似于动作的东西?

In example: 例如:

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"
    }
}

Then in a controller do: 然后在控制器中执行:

class TestController extends Controller
{
  public function actionAdd() {
    $wObj = new WTest;
    return $wObj->addThing();
  }
}

The issues with this way is that I loose all the parameters set when calling the widget in the form, since I am calling "new WTest", it is a new instance. 这种方式的问题是我在表单中调用窗口小部件时松开了所有参数集,因为我称之为“新WTest”,它是一个新实例。 I have tried using a static method too, but similar issue, any ideas? 我也试过使用静态方法,但类似的问题,任何想法?

UPDATE In the view, I am calling the widget like this: 更新在视图中,我调用这样的小部件:

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

Update: Remove private __contruct(), __clone() and use yii2 dependency injection. 更新:删除private __contruct(), __clone()并使用yii2依赖注入。 In class WTest , you should define some function and variables: 在类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;
}

And use in your action: 并在你的行动中使用:

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

Use in views: 在视图中使用:

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

Hope it helpful. 希望它有用。

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

Good luck and have fun! 祝好运并玩得开心点!

ThanhPV的答案并不完全正确,但它通过使用依赖注入引导我找到正确的方向:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM