1

I am building a shoping cart in Yii. Now I want to buid a function with name is afterCharged() the same as afterSave(). So how to can do it? Thank you in advance

Hoang NK
  • 540
  • 2
  • 8
  • 18

1 Answers1

3

As Michiel said you should use an event in your method

function charge(){ 
    //Perform charge related actions
    $this->onCharge(new CEvent($this));
    //... maybe some code over here after raising the event
}

public function onCharge($event){
    $this->raiseEvent('onCharge', $event);
}

Now you have to catch the raised event. So in this component you'll declare which class and which mehod need to catch it (for example in the init method)

//OtherClass need to catch the the charge event
$callback = array(new OtherClass,'afterCharge')
$component->onCharge = $callback;

So the method afterCharge of OtherClass will be called when charge() is executed.

By the way, the method afterCharge must have the following signature

function afterCharge($event) {
}

Sources:

darkheir
  • 8,844
  • 6
  • 45
  • 66
  • Also, I have a question : $component is global variable. Thank you very much – Hoang NK Mar 29 '14 at 08:15
  • No, this is the class that throw the event so you could replace it by $this – darkheir Mar 29 '14 at 08:18
  • And one question anymore:). So I can use event in Controller class ? – Hoang NK Mar 29 '14 at 08:33
  • Hum yeah i think. If i remember well events are implemented in CComponent so every class who inherit from it can use events. And CControler extends CComponent so it should work :-) – darkheir Mar 29 '14 at 08:37