简体   繁体   中英

Require dynamic class using namespace in PHP

I was studying a couple PHP frameworks and then decided to build my own, of course. But i'm facing one issue. I have a Router class that handles dynamically the HTTP requests and it basically explodes the URL into elements dividing it by the slash and storing it into an array, then a function is called to check if the first element is a valid Controller. If it is valid, the function should require it, but that's where i'm stuck, because it seems that i can't require a file like:

if (file_exists(CONTROLLERS_DIR . $this->url[0] . '.php')) { require \App\Controllers\$this->url[0] }

How can I require a file like that using namespaces?

Thanks.

"How can I require a file like that using namespaces?"
You can't. Namespaces have nothing to do with it.

"PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants." ~ Namespaces overview


require is about file dependancies, regardless the namespace:

if (file_exists(CONTROLLERS_DIR . $this->url[0] . '.php')) { 
    require(CONTROLLERS_DIR . $this->url[0] . '.php');
}

EDIT : You might want to instantiate a class using a namespace and class name retrieved in run-time though, ie something like:

namespace \App\Controllers;
class C {
    protected $_i;
    public function __construct($i){ $this->_i = $i; }
    public function foo(){ echo $this->_i; }
}

and somewhere:

$className = "C";                   // or $className = $this->whatever...
$class = "\\App\\Controllers\\".$className;
$instance = new $class(7);
$instance->foo();                   // outputs 7

I've built couple of frameworks and I understand what you trying to do... Basically when you have some path for example "HelloWorld\\addComment"

You want to create controller instance

\App\Controllers\HelloWorldController

There are multiple ways to solve it, the one I like is:

Using spl autoloader http://php.net/manual/en/function.spl-autoload.php

In the link I provided you got the examples you need.

Then you can end up just doing

$controller = new \App\Controllers\HelloWorldController();

You should put the HelloWorldController at the right namespace + maintain directory structure matching the namespace

app     
   Controllers
       HelloWorldController

spl autoloader will do the right including for you, often the default implementation is sufficient - but it is easy to create your own spl autoloader and register it

Later you can test if the $controller has the method you need via method_exist or reflection...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM