Slim Framework Base URL

梦想与她 提交于 2019-11-29 04:23:34

You need to set the base url manually FIRST before you can get it as in this:

$app->hook('slim.before', function () use ($app) {
    $app->view()->appendData(array('baseUrl' => '/base/url/here'));
});

http://help.slimframework.com/discussions/questions/49-how-to-deal-with-base-path-and-different-routes

With Slim v3, as it implements PSR7, you can get a PSR7 Uri object and call the getBasePath() method that Slim3 adds on it. Simply write:

$basePath = $request->getUri()->getBasePath();

From Slim v3 documentation :

Base Path

If your Slim application's front-controller lives in a physical subdirectory beneath your document root directory, you can fetch the HTTP request's physical base path (relative to the document root) with the Uri object's getBasePath() method. This will be an empty string if the Slim application is installed in the document root's top-most directory.

Be aware that the getBasePath() method is added by the framework and is not part of PSR7 UriInterface.

In a recent app where we're using Twig, we assign the httpBasePath as follows:

$view = $app->view()->getEnvironment();
$view->addGlobal('httpBasePath', $app->request->getScriptName());

The addGlobal() method is probably equivalent to $app->view()->appendData(), I'm not sure.

The advantage of using $app->request->getScriptName() is that we don't have to manually set a folder name or care what it is – one developer can have the repo located at http://example.localhost and another can have it at http://localhost/projects/slim and no configuration is required.

Try this in index.php to set the base url for the view

$app->hook('slim.before', function () use ($app) {
    $posIndex = strpos( $_SERVER['PHP_SELF'], '/index.php');
    $baseUrl = substr( $_SERVER['PHP_SELF'], 0, $posIndex);
    $app->view()->appendData(array('baseUrl' => $baseUrl ));
});

I can get the base url with {{ app.request.getRootUri }} (I'm using Twig template engine). Incidentally, this is the same as the 'SCRIPT_NAME' environment variable.

if you are using TWIG then in Slim v3 call -

{{ base_url() }}

or use {{ path_for('yourRouteName') }}

The easiest way to get the base url is to append the request url and the request root url like below: $req = $app->request; $base_url = $req->getUrl()."".$req->getRootUri()."/";

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!