PHP Booosta 3 Tutorial

PHP Booosta 3 Tutorial

Working with hook functions, dataobjects

Now let's add some additional functionallity to our application. We want to send an email to the user when he has registered to a course telling him the details of the course. So we add this method to the class definition in the script user_register.php:

protected function after_add_($data, $newid)
  {
    $course = $this->getDataobject('course', $data['course']);
    $name = $course->get('name');
    $starttime = $course->get('starttime');
    $endtime = $course->get('endtime');
    $description = $course->get('description');

    $lecturer = $this->getDataobject('lecturer', $course->get('lecturer'));
    $lecturer_name = $lecturer->get('name');

    $text = $this->t('You registered to the following course') . ':<br><br>';
    $text .= "$name<br>$starttime - $endtime<br>$lecturer_name<br>$description";

    $mail = $this->makeInstance('Email', $this->config('mail_sender'), $email, $this->t('Your course registration'), $text);
    $mail->send();
  }

Maybe you notice the difference in the parameters of the hook function after_add_() - which runs immediately after the record was inserted into the database - compared to the hook function before_add_() above. The second parameter is not an object. It is a numeric value representing the id of the inserted database record.There are some new things we see here:

  • The method getDatabobject. Dataobjects are objects that hold the content of a specific row in a database table. Which row this is is determined by the parameters of the constructor. The first is the name of the database table. Here it is "course". The second is the numeric id of the record or a sql clause identifying this record. As our HTML form sends a value for "course", we find that in the $data array inside the hook function.
  • We then work with this dataobject. With the get method we read the data from this object. Notice that we use the get method also to get the id of the lecturer and immediately use it for getting the dataobject for the lecturer.
  • We see a funny new method named t(). This is a translating method. We come to translations later on in this tutorial. For now just use the method.
  • In the last two lines we create the email and send it. We learn the method makeInstance() that creates an instance of a class. It does a little bit more then "new" does. So if you instantiate a class that is provided by a Booosta module, you should use makeInstance(). The first parameter of this method is the class name. The remaining parameters are the parameters of the constructor.


Previous - Next