The advantages of using the do_action function

WordPress action hooks define specific points in the execution process, where we can develop custom functions to modify existing behavior. In this scenario, we are calling the wpwaf_before_registration_form function within the class using do_action.

Unlike websites or blogs, web applications need to be extendable with future requirements. Think of a situation where we have to restrict the registration form to users from certain countries or provide different registration forms based on certain conditions. In a normal application, we will have to change the core application code to implement such features. Changing a working component is considered a bad practice in application development. Let's see why it's considered a bad practice by looking at the definition of the open/closed principle on Wikipedia:

"Open/closed principle states "software entities (classes, modules, functions, and so on) should be open for extension, but closed for modification"; that is, such an entity can allow its behavior to be modified without altering its source code. This is especially valuable in a production environment, where changes to the source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: the code obeying the principle doesn't change when it is extended, and therefore, needs no such effort."

WordPress action hooks come to our rescue in this scenario. We can define an action for the registration template using the add_action function, as shown in the following code:

    add_action( 'wpwaf_before_registration_form ', array( $this,     'custom_registration_form' ) ); 

Now you can implement this action multiple times using different functions. In this scenario, custom_registration_form can be used to display a new registration form. Inside this function, we can add a new template, as shown in the following code:

    public function custom_registration_form(){ 
if ( !is_user_logged_in() ) {
include WPWAF_PLUGIN_DIR . 'templates/custom-register- template.php';
exit;
}
}

Now the custom_registration_form function is executed before the primary function. So, we can remove the primary registration template and override it with our own template. Also, we can use this function to check the user's country and redirect the user to a different page when the user is not allowed to access the registration form. With this technique, we have the capability of adding new functionalities as well as changing existing functionalities without affecting the already written code.

We have implemented a simple controller which can be quite effective in developing web application functionalities. In the following sections, we will continue the process of implementing registration on the frontend with custom templates.