Chapter 2.2: Add Class Method

Your application would have more customized actions than the few standard RESTful verbs. So one of your daily works would be to add new methods to model, or to override the existing RESTful methods. When adding new method, please follow the rules:

 

Rule 1: Use the action as the method name.

For example, to add a new action findFriends:

sub findFriends {
  my $self = shift;
  my $extra = shift;
  ...
  return;
}

Note that the following attributes can be taken as granted and are good enough for you to finish any sophisticated method.

  • $self->{ARGS}: the input data.
  • $self->{DBH}: the standard DBH handler.
  • $self->{STORAGE}: the pre-defined caching object.
  • $self->{LOGGER}: the logger.

 

Rule 2: return nothing for success, otherwise return the error found.

The last statement in a class method is always

return;

If any error is met, return that error code or an explanation string. The error will be shown in HTML or API.

 

Rule 3: Save main output data into LISTS

The resultant data are always assigned to $self->{LISTS} . Usually you create empty array reference, run a relevant database method as described in this section, which will fill in the array. For example, to search for one’s friends:

sub findFriends {
  my $self = shift;
  $self->{LISTS} = [];
  my $err = $self->select_sql($self->{LISTS},
    "SELECT * FROM tbl_friends WHERE user_id=?",
    $self->{ARGS}->{user_id});
  return $err if $err;

  return;
}

Or even simpler:

sub findFriends {
  my $self = shift;
  $self->{LISTS} = [];
  return $self->select_sql($self->{LISTS},
    "SELECT * FROM tbl_friends WHERE user_id=?",
    $self->{ARGS}->{user_id});
}

In HTML template or API, the data will be returned as the value of key findFriends.

All other type of data can be saved to $self->{OTHER}, using your customized key names. They will be output as multiple key-value pairs in HTML or API.