As you can see, it’ll call the execute method defined in the same file until $action evaluates to false. This means that if the method of the controller returns an action object, OpenCart will execute that action before proceeding further. We could take advantage of this and call the other action from within the action itself. Let’s see how to accomplish that! ## Call the Common Controller and View Setup Now, let's create a preaction_demo.php file under the preactiondemo directory with the following contents. If $flag is true, we’ll return the instance of the action class, and as we’ve just seen, if the dispatch process receives an action object, it’ll continue with that action. So in this case, it will call the setup method of the common controller. Recall the common.php file which we created in the earlier section.

The important thing to note is that we’re passing array('controller' => $this, 'method'=>'index') as an argument, which will be eventually passed to the first argument of the setup method in the common controller. It’ll help us to get back to the index method of the preaction_demo controller after initialization of variables. Further, in the setup method we’ve defined a few common variables like header, footer, etc. And finally, we’re transferring control back to the original controller from where the setup method was called using the following statement. Of course, we need to pass the variables initialized in the setup method via $data to the original controller so that it can be utilized there, which is the main purpose of this article. It’s passed as the first argument of the above method call. The second argument is very important as it’ll be initialized to the \$flag variable. We’re deliberately doing this to avoid infinite looping.

Finally, let’s go ahead and set up our view file at catalog/view/theme/default/template/preactiondemo/preaction_demo.tpl with the following code.

Now that we've finished with the setup, go ahead and open the URL http://youropencartstoreurl/index.php?route=preactiondemo/preaction_demo in your browser. You should see the message "I've been set by the 'setup' method from the 'common' controller file." in that page!

So, in this way you could set up the common code in one place, and call that action from the other controllers. Certainly, it’ll avoid code duplication, and it’s easier to change the code which is common across the modules.

## Conclusion

Today, you’ve learned a cool trick in OpenCart: how to call an action from within the action! Of course, there are other ways to achieve that, but it’s something I’ve got in my mind lately and thought I should share it with you and get your feedback!