Sergey Romanov
Sergey Romanov

Reputation: 3080

Access function variable inside class method

I searched and there are a lot of answers but I cannot find one I need because I do not know even how to create correct question. here is the example.

$app->map('/v1/:module/:group/:action(/:id)', function ($module, $group, $action, $id = NULL) use ($app) {

    $method = ucfirst($app->request->getMethod());
    $file = "modules/{$module}/{$group}/{$method}{$action}.php";

    if(!file_exists($file)) {
        $app->halt(404, Error::_('API Processor was not found!', 404));
    }

    include_once $file;

    $app->stop();
})

This is my API method by slim restful framework. Now for this Error::_('API Processor was not found!', 404) I have

class Error {
    public static function _($msg, $code = 500) {
        global $module, $group, $action;

        return json_encode(array(
            'error' => true,
            'code' => $code,
            'message' => $msg,
            'module' => $module
        ));
    }
} 

What I want os to get access to $module, $group, $action variables without passing them into that function. But in my case $module is NULL.

{
    "error":true,
    "code":404,
    "message":"API Processor was not found!",
    "module":null
}

Possible?

Upvotes: 1

Views: 335

Answers (1)

Jeremy Kendall
Jeremy Kendall

Reputation: 2869

You should be able to meet those requirements, if I understood your question correctly, by using the Slim Error Handling functionality. If it were my project, I'd create a custom exception to throw wherever you're planning on using your custom error function.

NOTE: All of the code below is untested and written off the top of my head. Caveat emptor and all that.

class CustomErrorException extends \Exception
{
}

Then I would throw that exception wherever I'd otherwise use my custom error function.

if(!file_exists($file)) {
    throw new CustomErrorException('API Processor was not found!', 404);
}

Finally, I'd write an error function that looks something like this:

$app->error(function (\Exception $e) use ($app) {

    if ($e instanceof CustomErrorException) {
        // Parse $path to get $module, $group, and $action
        // (Seems like that would work based on the route in your example: '/v1/:module/:group/:action(/:id)')
        $path = $app->request->getPath();

        // Possible new method signature for Error::_
        Error::_($e->getMessage(), $e->getCode(), $module, $group, $action);

        // Render an error page, $app->halt(), whatever.
    }
});

That should help DRY your code up a bit and allow you to dump those global variables.

Upvotes: 1

Related Questions