如何使用RequestStackContext symfony类获取Base Path?

时间:2017-11-03 19:58:54

标签: php symfony

阅读此http://api.symfony.com/3.2/Symfony/Component/Asset/Context/RequestStackContext.html 我用

use Symfony\Component\Asset\Context\RequestStackContext;
use Symfony\Component\HttpFoundation\RequestStack;

$con = new RequestStackContext(new RequestStack);
print($con->getBasePath());

但我什么都没得到,也没有错误,只是空白。我做错了什么?

编辑:

实际上我想将它作为第三个参数传递给PathPackage,但它什么都不返回。它应该返回RequestStackContext中的getBasePath。怎么解决?我的代码如下:

use Symfony\Component\Asset\Packages;
use Symfony\Component\Asset\PackageInterface;
use Symfony\Bridge\Twig\Extension\AssetExtension;
use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\PathPackage;
use Symfony\Component\Asset\UrlPackage;
use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;
use Symfony\Component\Asset\Context\RequestStackContext;
use Symfony\Component\HttpFoundation\RequestStack;


$versionStrategy = new EmptyVersionStrategy();
$namedPackages = array(
    'img' => new PathPackage('images', $versionStrategy, new RequestStackContext(new RequestStack())),
);
$defaultPackage = new Package($versionStrategy);
$packages = new Packages($defaultPackage, $namedPackages);
$twig->addExtension(new AssetExtension($packages));

2 个答案:

答案 0 :(得分:0)

它是空白的,因为您创建了一个新的RequestStack而不是Symfony提供的RequestStack,例如在控制器中应该这样做:

public function indexAction(Request $r): Response
{
    print($r->getBasePath());
    die();
}    

答案 1 :(得分:0)

尝试一下:

use Symfony\Component\HttpFoundation\Request;

然后:

$request = Request::createFromGlobals();
echo $request->server->get('CONTEXT_DOCUMENT_ROOT');

Symfony v5.1