Using EVENT_AFTER_SEND

Hi,

I’m trying to understand EVENT_AFTER_SEND.

I’ve got a very simple test script to try to harness that event, but it’s not working. I’m not sure what the issue is:


    public function actionThankYou()

    {

        $order = Order::findOne(333195);

        $this->on(Response::EVENT_AFTER_SEND, function ($event) {

            file_put_contents('/tmp/debug', "hello world\n");

        });

        return $this->render('thank-you', ['order' => $order]);

    }



I ought to see a file “debug” in /tmp, but I don’t.

If it’s relevant, the larger problem that I’m trying to solve is:

I’d like to send an “thank you” email in an eCommerce application, but only after the Thank You page is shown to the user. The reason is that our mail provider intermittently times out - when this happens, in our current application, the Thank You page hangs, waiting for the mail server, and doesn’t render the page, causing confusion for the user.

I’m going to take a crack at answering my own question here - it’s a guess, but… the same code works just fine when I substitute Controller::EVENT_AFTER_ACTION for Response::EVENT_AFTER_SEND… or:


 public function actionThankYou()

    {

        $order = Order::findOne(333195);

        $this->on(Response::EVENT_AFTER_ACTION, function ($event) {

            file_put_contents('/tmp/debug', "hello world\n");

        });

        return $this->render('thank-you', ['order' => $order]);

    }

so I wonder if the controller is out of scope by the time EVENT_AFTER_SEND gets triggered.

If that’s the case, then I’m not sure how I’m supposed to trap that action. Has anyone been able to do that?

just for the record here - I was able to get it to respond to EVENT_AFTER_SEND by doing the following:


public function actionThankYou()

    {

        $order = Order::findOne(333195);

         Yii::$app->response->on(Response::EVENT_AFTER_SEND, function ($event) {

            file_put_contents('/tmp/debug', "hello world\n");

        });

        return $this->render('thank-you', ['order' => $order]);

    }

However, this didn’t work as I expected. I was hoping it would render the page first - then respond to the event… it didn’t… this test, still hung for 30 seconds before showing the Thank You page:


public function actionThankYou()

    {

        $order = Order::findOne(333195);

         Yii::$app->response->on(Response::EVENT_AFTER_SEND, function ($event) {

            $start = time();

            $end = $start + 30;

            while (time() < $end) {

            }

            file_put_contents('/tmp/debug', "hello world\n");

        });

        return $this->render('thank-you', ['order' => $order]);

    }