Welcome Guest, Not a member yet? Register   Sign In
DRY approach with different request type
#1

Hi! I've multiple controller classes, each containing a lot of controllers.

Class1/ControllerA
Class1/ControllerB
Class1/ControllerC
Class2/ControllerD
Class2/ControllerE
Class2/ControllerF
...

Each controller, regardless of the containing class, must execute a check before executing the rest of the function. In order to avoid adding the same code to each controller I was thinking about putting common code into an helper function called once from each class' constructor.
The check function must interrupt the execution flow, then show an error page. This behaviour can be easily obtained using redirect or show_404 functions.

PHP Code:
class Class1 {
    
    public function 
__construct() {
        
parent::__construct();
        
        
check_failed();
    }
    
}

// somewhere else...

function check_failed() {
    if (
check_condition_failed) {
        
redirect(); // or show_404
    
}


The problem is that I cannot predict if the request it's a plain http request or an ajax request! Please, read comments into following code

PHP Code:
class Class1 {
    
    public function 
__construct() {
        
parent::__construct();
        
        
check_failed();
    }
    
    public function 
index() {
        
// unfortunately index is reached if this is an ajax request
    
}
    
}

// somewhere else...

function check_failed() {
    if (
check_condition_failed) {
        if (
is_ajax_request()) {
            
// what to do at this point in order to interrupt the __construct execution?
        
}
        else {
            
redirect(); // or show_404
        
}
    }


So I'm looking for a common pattern that minimizes code duplication about routine checks and manages correctly both plain and ajax requests. Any suggestion? Thanks in advance!
Reply


Messages In This Thread
DRY approach with different request type - by geekita - 10-17-2016, 03:54 PM



Theme © iAndrew 2016 - Forum software by © MyBB