我正在为我的一个库编写一个路由器类。此类将保留某些路径的位置,但我想知道是否应该使用“智能”绝对路径、相对路径或两者(对于这种情况)将是同一件事。
Obs.1:当我写“智能”绝对路径是因为即使管理员将库移动到另一个位置,这个绝对路径也可以工作。
Obs.2:Stack 对此主题还有其他问题,但看起来它们与我要查找的内容无关,所以我提出了这个问题。
第一个解决方案:
MyVendor/src/class/MyVendor/MyNamespace/Router.php
使用“智能”绝对路径
namespace MyVendor\MyNamespace;
class Router
{
private $root;
private $cache;
public function __construct()
{
$this->setRootPath();
$this->cache = "{$this->root}var/cache/";
}
public function setRootPath()
{
$currentDir = __DIR__;
$exploded = explode("/", $currentDir);
array_pop($exploded); // Removing MyNamespace
array_pop($exploded); // Removing MyVendor
array_pop($exploded); // Removing class
array_pop($exploded); // Removing src
$this->root = implode("/", $exploded)."/";
}
}
第二种解决方案:
MyVendor/src/class/MyVendor/MyNamespace/Router.php
使用相对路径
namespace MyVendor\MyNamespace;
class Router
{
private $root;
private $cache;
public function __construct()
{
$this->setRootPath();
$this->cache = "{$this->root}var/cache/";
}
public function setRootPath()
{
$this->root = __DIR__."/../../../../";
// ..(pointing to MyVendor)/..(pointing to class)/..(pointing to src)/..(pointing to the root, MyVendor)
}
}
Obs.3:请参阅第一个解决方案将使用以下链接:
root => `/var/www/myproject/vendor/MyVendor/`
cache => `/var/www/myproject/vendor/MyVendor/var/cache`
第二个将使用如下链接:
root => `/var/www/myproject/vendor/MyVendor/src/class/MyVendor/MyNamespace/../../../../`
cache => `/var/www/myproject/vendor/MyVendor/src/class/MyVendor/MyNamespace/../../../../var/cache/`
Obs.4:初始处理(使用array_pop)与我无关。
那么,我应该使用什么解决方案,为什么?还有另一种更好的方法吗(如果是,请编写一个路由器类替代方案)?