phpAspect Logo

Chapter 7. Advices

Advices define the code to apply on pointcuts.

Before advice

Before advice executes prior to the join point:

Example 7.1: Before advice.

<?php
    before(): call(HelloWorld::say(0)){
        echo "Before saying Hello World\n";
    }
?>


After advice

After advice executes following to the join point:

Example 7.2: After advice.

<?php
    after(): call(HelloWorld::say(0)){
        echo "After saying Hello World\n";
    }
?>


Around advice

Around advice replace the joinppoint execution. In an around advice, the proceed() call function represents the joinpoint execution.

Example 7.3: Around advice.

<?php
    around(): call(HelloWorld::say(0)){
        echo "50% chance to say Hello World\n";
        if(rand(0, 1)){
            proceed();
        }
    }
?>


The return statement can be used in an around advice. The returned expression will replace the joinpoint execution.

Example 7.4: Return statement in an around advice.

<?php
    around(): exec(Cart::getAmount(0)){
        //Give a 20% discount
        $amount = proceed();
        return $amount-0.2*$amount;
    }
?>