yii2 container->set使用示例

 

<?php
class TestController extends Controller
{
    public function actionIndex()
    {
        $order = [
            'id' => 1,
            'order_no' => 20201118
        ];
        $params = [
            'id' => 1,
            'name' => 'xiaoming'
        ];
        \Yii::$container->set(TestPay::class, TestOrder::class, [$params, $order]);
        \Yii::$container->invoke([$this, 'pay']);
        exit();
    }

    public function pay(TestPay $testPay)
    {
        $testPay->notify();
        $testPay->syncSms();
    }

}

abstract class TestPay
{
    public $params;
    public $order;

    public function __construct($params, $order)
    {
        $this->params = $params;
        $this->order = $order;
    }

    abstract function validate();

    abstract function notify();

    public function syncSms()
    {
        print_r('syncSms');
        echo PHP_EOL;
    }
}

class TestOrder extends TestPay
{
    public $params;
    public $order;

    public function __construct($params, $order)
    {
        parent::__construct($params, $order);
    }

    public function validate()
    {
        print_r('validate');
        echo PHP_EOL;
        print_r($this->params);
        echo PHP_EOL;
    }

    public function notify()
    {
        print_r('notify');
        echo PHP_EOL;
        print_r($this->order);
        echo PHP_EOL;
    }
}

效果截图【/test/index】:

 

posted @ 2020-11-19 10:14  一个人的孤独自白  阅读(377)  评论(0编辑  收藏  举报