Aleksey Bykov Aleksey Bykov - 4 months ago 41
PHP Question

Is there AOP for Yii 2?

I want to know how much time is executed every action. The easiest/ correct way would be to use AOP.

I'd like to have something like this:

/**
* @FLOW3\Before("method(.*->action.*())")
*/
public function markFirstTimeTag() {
// Do something here.
}

...

/**
* @FLOW3\After("method(.*->action.*())")
*/
public function markSecondTimeTag() {
// Do something here.
}


I read about the FLOW3 and this framework I liked. But this is a full-stack framework itself.

Is there the implementation of AOP pattern for Yii 2?

I would be very grateful for the information. Thanks to all.

Answer

I usually use Logging to profile my code.

Yii::trace('starting some event);
foreach(..)
{
    ...
}
Yii::trace('some event done');

This traces can be found in the Logs section of the debug bar.

This could be used in combination with beforeAction() and afterAction() (not tested)

public function beforeAction($action)
{

    if (!parent::beforeAction($action)) {
        return false;
    }

    Yii::trace($action->id.' started');

    return true; // or false to not run the action
}

public function afterAction($action, $result)
{
    $result = parent::afterAction($action, $result);
    Yii::trace($action->id.' ended');
    return $result;
}

I also found Performance Profiling in the docs, but i have not tried any of the solutions.