【问题标题】:How to get the root URL to Slim application in a subdir?如何在子目录中获取 Slim 应用程序的根 URL?
【发布时间】:2016-01-15 21:51:54
【问题描述】:

我必须用 PHP 做一个网站,我选择使用 Slim 和 Twig。但是我的上级不希望我使用虚拟主机。因此,当我使用 MAMP 测试网站时遇到问题,因为该网站位于子目录中,例如 http://localhost:8888/subdir

当我尝试访问资产时,我不能使用绝对路径,因为它会迫使我写 /subpath/path/to/asset。但是当我们部署应用程序时,不会有子路径。我怎样才能像有虚拟主机一样根网站?

你可以在下面看到我的一些代码:

index.php

<?php
require 'vendor/autoload.php'; 

include 'database.php';

use app\controller\ConfigController;

$app = new \Slim\Slim();

$app->get('/', function () {
    echo "accueil";
})->name("root");

$app->group('/Admin', function () use ($app) {

    $app->get("/", function (){
        $ctrl = new ConfigController();
        $ctrl->index();
    })->name("indexAdmin");

});

.htaccess(在 localhost:8888/subdir 中)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

ConfigController(调用函数)

public function index() {
    $loader = new \Twig_Loader_Filesystem("app/view/Admin");
    $twig = new \Twig_Environment($loader);
    $template = $twig->loadTemplate('Index.twig');
    echo $template->render(array(
        'css' => "admin.css"
    ));
}

模板由 Twig 环境调用

<!doctype html>
<html lang="fr">
<head>
    <link rel="stylesheet" type="text/css" href="/app/assets/stylesheets/{{ css }}">
</head>
<body>
[...]

当我在谷歌和 Stack Overflow 上搜索时,每个人都说要做一个虚拟主机,但我做不到。会不会有其他解决方案?

【问题讨论】:

  • 嘿@Amanite,欢迎来到 S.O.您是否正在使用 slim/views 包将 Twig 集成到您的应用程序中?

标签: .htaccess twig mamp slim subdirectory


【解决方案1】:

如果您使用slim/views package 将Twig 集成到您正在编写的应用程序中,则可以将该包中的TwigExtension 添加到您的Twig 实例并为您的资产使用siteUrl 函数。这样:

<link rel="stylesheet" href="{{ siteUrl('path/to/asset/style.css') }}">

如果您不使用该包,您可以创建自己的函数来获取应用程序 URL。像这样的:

function siteUrl($url) {
    $req = Slim::getInstance()->request();
    $uri = $req->getUrl() . $req->getRootUri();
    return $uri . '/' . ltrim($url, '/');
}

【讨论】:

  • 非常感谢您!我将在星期一尝试 thqt(我在周末无法访问该项目)
猜你喜欢
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 2023-03-10
  • 2011-03-28
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多