2

I'm trying to create a small RESTful API for my database and I encountered a problem creating controller object dynamically based on user request, because all my code is using namespaces and just doing:

$api = new $controllerName($request);

Won't work. Because $controllerName would resolve to "ReadController", but is actually \controllers\lottery\ReadController hence the error

The whole part of defining the path to the class is:

if ($method === 'GET') {
    $controllerName = 'ReadController';
    // @NOTE: $category is a part of $_GET parameters, e.g: /api/lottery <- lottery is a $category
    $controllerFile = CONTROLLERS.$category.'/'.$controllerName.'.php';
    if (file_exists($controllerFile)) {
        include_once($controllerFile);

        $api = new $controllerName($request);
    } else {
        throw new \Exception('Undefined controller');
    }
}

And the declaration of ReadController in core\controllers\lottery\ReadController.php

namespace controllers\lottery;

class ReadController extends \core\API {

}

Any ideas how to dynamically create the object?

Thanks!

1 Answer 1

8
$controllerName = 'controllers\lottery\ReadController';
new $controllerName($request);

Classes instantiated from strings must always use the fully qualified class name.

Sign up to request clarification or add additional context in comments.

4 Comments

That simple... damn.. Thanks, it worked. Will accept the answer in 10min.
Yes, I had similar problem. The only improvement to answer is: why it is so. And it's so because PHP will replace namespace aliases to it's full path on interpretation, so aliases will not persist in opcodes and VM will know nothing of them
@Alma I think that's way too detailed an explanation. It's as simple as stackoverflow.com/a/16808358/476
Fair enought. I thought OP was asking about ReadController as an alias for \controllers\lottery\ReadController

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.