按照建议,一个简单的解决方案是创建一个配置文件(json、xml 或 php — 我将使用最后一个),其中包含在您的域根目录中找到的重要信息,在本例域名:
/config.php
<?php
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('INCLUDES',ROOT_DIR.DS.'includes');
define('FUNCTIONS',INCLUDES.DS.'functions');
# Define base domain
define('SITE_URL','//localhost');
这只会结合项目路径(如果已设置)。
/includes/functions/asset.php
function asset($path=false)
{
# Check if a project folder is set
$proj = (defined('PROJECT_NAME'))? PROJECT_NAME : '';
# See if the current mode uses SSL
$protocol = (isset($_SERVER['HTTPS']))? 's' : '';
# Create a path (if no project, it will leave "//" so you need to replace that)
$final = str_replace('//','/','/'.trim($proj,'/').'/'.ltrim($path,'/'));
# Send back full url
return "http{$protocol}:".SITE_URL.$final;
}
这基本上就是你会做的。
/index.php
<?php
# Include config
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Include the asset function
include_once(FUNCTIONS.DS.'asset.php');
# Define the current project. If you are always accessing this,
# then you may want to have it in the config, but if you are doing multiple projects
# you can leave the define in the root of each project file
define('PROJECT_NAME','todo-oop');
# Use asset to write the asset path
echo asset('/partials/css/todo.css');
应该这样写:
http://localhost/todo-oop/partials/css/todo.css
如果您没有定义项目:
http://localhost/partials/css/todo.css
如果您只有一个使用单独配置访问的项目,您还可以更改 SITE_URL 以包含项目目录:
define('SITE_URL','//localhost/todo-oop');
正如@Loek 所展示的,您可以使用框架来创建此类路径等,或者您可以创建类(如果您有足够的信心这样做) 基本上可以完成我的工作演示。使用类/框架的好处是它们将具有更大的灵活性和动态交互,但是对于一个非常直接的过程,您可以使用上述方法来完成这些类型的路径。