我已经编写了我的Route类,它从服务器的DOCUMENT_ROOT开始时效果很好。但是现在我必须从深层目录中使用它并且问题开始了。现在我要告诉你我的index.php和route.php文件。我想问你如何在不手动编写服务器上的目录的情况下使用它? (当然没有解析)。或者一般来说,我如何从服务器上的任何目录开始工作? DIR 显示本地计算机上的目录或工作原理?
/用户/用户名/ PhpstormProjects /项目名称
但它适用于像
这样的URI的用户名/ PhpstormProjects /项目名称/
的index.php
<?php
include_once 'vendor/autoload.php';
ini_set('display_errors', 1);
error_reporting(E_ALL);
//session_start();
include_once 'components/route.php';
//put here the directory with index.php (form from ROOT: cat1/ca2/ )
$GLOBALS['base_dir'] = 'username/PhpstormProjects/projectname/';
$router = new Route();
$router->start();
route.php
<?php
class Route
{
private $aRouts = [
];
public function __construct()
{
$routes = './config/routes.php';
$this->aRouts = include($routes);
}
private function getURL()
{
//get request string
if (!empty($_SERVER['REQUEST_URI'])) {
return trim($_SERVER['REQUEST_URI'], '/');
}
return null;
}
public function start() {
$uri = $this->getURL();
foreach ($this->aRouts as $uriPattern => $path) {
if (preg_match("~$uriPattern~",$uri)) {
$url = $GLOBALS['base_dir'];
//cut the first part of URL with directory
$cutDir = preg_replace("~$url~","","$uri");
//black magic (change reg exp)
$internalRoute = preg_replace("~$uriPattern~","$path","$cutDir");
$segments = explode('/',$internalRoute);
$controllerName = array_shift($segments).'Controller';
//take name of file with class
$controllerName = ucfirst($controllerName);
//take name of method
$actionName = 'action'.ucfirst(array_shift($segments));
$parametrs = $segments;
//connect files
$controllerFile = './controllers/'.$controllerName.'.php';
if(file_exists($controllerFile))
{
include_once $controllerFile;
}
//create new controller object
$classObject = new $controllerName();
$result = call_user_func_array(array($classObject, $actionName), $parametrs);
if($result != NULL){
break;
}
}
}
}
}
答案 0 :(得分:0)
在所有页面中尝试以下代码
$path = $_SERVER['DOCUMENT_ROOT']."/Users/username/PhpstormProjects/projectname";
现在路径将拥有完整路径。因此,您可以在任何页面上使用它,并且不会产生问题。
$_SERVER['DOCUMENT_ROOT']
将根据路径的一部分添加根路径。所以它总是会引用完整的路径