Question

we have a static method in a Cake component. The task was to redirect the user to the login page, if this component throws a specific error. The current (working) solution is:

class SomeComponent extends Component {

    static $controllerObject; 

    function startup(&$controller) {        
        SomeComponent::$controllerObject =& $controller;
    }

(...)

    public static function decodeResponse($response) {
        if($response == null || trim($response) == '') {
            return null;
        }
        $result = json_decode($response, true);
        if($result == null) {
            throw new FatalErrorException('Could not parse api server response: ' . $response);
        }
        if(isset($result['error'])) {
            if ($result['error'] === "IncorrectCredentialsException") {
                self::$controllerObject->Session->destroy();                
                self::$controllerObject->Session->setFlash(__('Your session has ended. Please log in again.', true), 'default', array(), 'error');                                
                self::$controllerObject->redirect(array(
                    'language' => Configure::read('Config.language'),
                    'controller' => 'users', 
                    'action' => 'login'
                )); 

            }
            else { throw new ApiServerException($result); }
        }
        return $result;
    }

However, my team colleague, who is responsible for the software quality, doesn't find this solution satisfying. He says: "pls find a better way to pass the controller to the decode method. Setting the controller as static variable is not the best way".

Is there any better way to do this?

Was it helpful?

Solution

I think the problem is that your method does two different things: decoding and error handling. Instead of handling the IncorrectCredentialsException inside your method, I would move this functionality to where you handle the other exceptions and just throw an IncorrectCredentialsException in your method. With this change you no longer need to access the controller in your static method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top