JReviews:Macroable Controllers

From JReviews Documentation
Jump to: navigation, search

Starting with JReviews 3.6.4.1 it is possible to override specific routing methods in controllers without having to copy the entire controller file to overrides. To get started with this override feature you would create an empty controller in the same path as regular controller files (mentioned above), but add the _macros suffix. So for example to override a routing method in, categories_controller.php, you create an empty file named categories_controller_macros.php. Inside this file, you override an existing routing method like this:

<?php
defined('MVC_FRAMEWORK') or die;
 
CategoriesController::macro('category_override', function() {
 	return "Hello World!";
 });

The above code overrides the CategoriesController::category method and will output "Hello World" in category pages. Notice that the macro name needs to be the original routing method "category" with the "_override" suffix => category_override.

This approach ONLY works for routing methods, which are methods that are directly called when routing a request. Any internal methods that used within the controller class cannot be overridden like this, but you could create new methods using the same approach and then call these new methods from within your macro override. For example, the following code will also output "Hello World!" in the category page, but it does so by calling a new 'custom_method' that is also dynamically created through a macro:

<?php
defined('MVC_FRAMEWORK') or die;
 
CategoriesController::macro('category_override', function() {
	return $this->custom_method("Hello World!");
});
 
CategoriesController::macro('custom_method', function($string) {
	return $string;
});

This approach, allows you to override internal methods, in addition to routing methods. Just make sure that you use a different method name for your internal method overrides because creating a macro using an existing method name will not allow the system to use the macro. The original method will be used instead. For example, creating a macro for 'category' using CategoriesController::macro('category', function() {}) won't work because the original category method will be called instead of your macro.