Current Record: GettingStarted:triggers #81

Triggers Triggers are methods that can be defined to carry out custom behaviors when certain events occur in the application (e.g., when re...

Current Record: GettingStarted:triggers #81

Triggers Triggers are methods that can be defined to carry out custom behaviors when certain events occur in the application (e.g., when re...

Triggers

[Permalink]

Triggers

Triggers are methods that can be defined to carry out custom behaviors when certain events occur in the application (e.g., when records are saved, inserted, or deleted).

Triggers are generally regarded as one of the more advanced features of database applications. Despite the "advanced" status of triggers, however, they are very simple to use and can be leveraged by Xataface developers to add powerful functionality to their applications.

So what can you do with a trigger?

  • Send a confirmation email every time a new record is inserted into a table.
  • Delete records related to a record that is being deleted (to maintain the consistency of the database).
  • Add custom logging functionality.
  • Add extra permissions or validation rules (although these are probably better handled with the validation framework).

You can really do just about anything you want with a trigger. A trigger is essentially just a custom PHP method that is called by Xataface when certain events occur.

What triggers are available?

As of version 0.5.3 Xataface supports the following triggers:

  • beforeSave : called just before a record is saved (either inserted or updated).
  • afterSave : called just after a record is saved (either inserted or updated).
  • beforeInsert : called just before a record is inserted.
  • afterInsert : called just after a record is inserted.
  • beforeUpdate : called just before a record is updated.
  • afterUpdate : called just after a record is updated.
  • beforeDelete : called just before a record is deleted.
  • afterDelete : called just after a record is deleted.
  • beforeAddRelatedRecord : called just before a related record (new or existing) is added to a relationship.
  • afterAddRelatedRecord : called just after a related record (new or existing) is added to a relationship.
  • beforeAddNewRelatedRecord : called just before a new related record is added.
  • afterAddNewRelatedRecord : called just after a new related record is added.
  • beforeAddExistingRelatedRecord : called just before an existing related record is added.
  • afterAddExistingRelatedRecord : called just after an existing related record is added.

How do you define a trigger?

Triggers are always defined as methods of the delegate class for a table. As an example, suppose we wanted to add a trigger to send a the administrator a notification email every time a new record is inserted into the 'Course' table. The steps would be as follows:

  1. Create a delegate class for the 'Course' table (if one does not already exist) by creating a file named 'Course.php' inside the 'tables/Course' directory.
  2. Add the following to the Delegate class file to make it a valid delegate class:
    <?
    class tables_Course {}
  3. Okay, we want our trigger to be called every time a record is inserted. There are 2 possible triggers that can be defined, then:
    • beforeInsert
    • afterInsert

    In this case it is probably more appropriate to define the afterInsert trigger because we really only want to send the notification email after the insert has successfully taken place. Therefore, we will define the afterInsert() method in our delegate class as follows:

    <?
    class tables_Course {
        ....
        /**
         * Trigger that is called after Course record is inserted.
         * @param $record Dataface_Record object that has just been inserted.
         */
        function afterInsert(&$record){
            mail('admin_email@yourdomain.com','Subject Line', 'Message body'); 
        }
    }
  4. That's all for now. The afterInsert() method defined above will automatically be called every time a record is inserted into the Course table. This method, as we have defined it, will send a notification email to the administrator email.

Sending feedback to the user

The above example sends the email without any feedback to the application's user of whether the email succeeded or not. When the user inserts a new Course he will only see that the record was succesfully saved, but no mention is made of the email. The following example does the same thing as the previous one, except that it sends a confirmation to the user when the email has been successfully sent:

function afterInsert(&$record){
    $response =& Dataface_Application::getResponse();
        // get reference to response array

    if ( mail('shannah@sfu.ca', 'Subject Line', 'Message Body') ){
        $response['--msg'] .= "\nEmail sent to shannah@sfu.ca successfully.";
    } else {
        $response['--msg'] .= "\nMail could not be sent at this time.";
    }
}

Now, when the user inserts a new record he will see a confirmation as follows:

http://framework.weblite.ca/documentation/tutorial/getting_started/trigger-after-insert-confirm.gif

Notice that we used the Dataface_Application::getResponse() function to obtain a reference to the application's response array. The response array is just a global array that is shared by the entire application that allows you to pass information easily from one part of the application to another. The '--msg' index of array is where you can place text that you wish to have displayed to the user as a confirmation.

Note: It is important to use '=&' to assign the result of Dataface::getResponse() and not just '='. e.g.:

$response =& Dataface_Application::getResponse(); // correct!
$response = Dataface_Application::getResponse(); // WRONG!!

This is because we need a reference to the response array, not a copy. That way when we assign a value to the '--msg' index it is applied to the actual response array and not a copy of it.

Handling Errors

The above method of sending messages to the user is useful for notifications and confirmations. However, in some cases you want to inform the user that an error occurred and cancel further operations. For example you may want to disallow a record to be inserted if a confirmation email cannot be sent. In this case we define the beforeInsert() trigger and return a PEAR_Error object if the email fails as follows:

<?
class tables_Course {
    function beforeInsert(&$record){
        $response =& Dataface_Application::getResponse();
        if ( mail('shannah@sfu.ca', 'Notification', 'Your record was created')){
            $response['--msg'] .= "\nEmail sent successfully to shannah@sfu.ca";
        } else {
            return PEAR::raiseError(
                "Errors occurred while sending email.  Record could not be inserted",
                 DATAFACE_E_NOTICE
            );
        }
    }
     
}

This trigger is called just before a course record is inserted into the database. If the mail succeeds, then the user sees a success message. If it fails, on the other hand, the insert is cancelled, and the user will see a message as follows:

http://framework.weblite.ca/documentation/tutorial/getting_started/trigger-error.gif

Note: Notice the use of the DATAFACE_E_NOTICE constant as a second parameter for PEAR::raiseError(). This is important as without it Xataface will display a less user-friendly error message complete with stack trace. If the error is such that you want a complete stack trace, you can use the DATAFACE_E_ERROR constant instead.

blog comments powered by Disqus
Powered by Xataface
(c) 2005-2024 All rights reserved