我正在使用 Php 和 Phalcon 框架构建一个 Ajax 驱动的 Web 应用程序。
当用户访问该网站时,他的请求将在我的 pageNotFound 方法中处理,该方法将呈现 index.php
View ,该 View 将调用我的服务器添加 Page
当前 url 的前缀以在 div 中加载 HTML。
因此 www.mywebsite.com/home
将调用我的服务器 www.mywebsite.com/Page/Home
,它将在 div 中呈现 html。
如果用户试图直接从其浏览器中的 url 输入访问 Page
url,我想将用户重定向到主页。
但是当我尝试重定向他时,url 变为:ww.mywebsite.com/public/index/index
有人知道 Phalcon 为什么要这样做吗?什么可能是解决我的问题的方法?
我能够使用以下代码做我想做的事情的唯一方法:
header("location:/");
这是我的原始代码。
<?php
try {
//Register an autoloader
$loader = new \Phalcon\Loader();
$loader->registerDirs(
array(
'../app/controllers/',
'../app/models/'
)
)->register();
//Create a DI
$di = new Phalcon\DI\FactoryDefault();
$app = new \Phalcon\Mvc\Micro();
$di->set('view', function() {
$view = new Phalcon\Mvc\View\Simple();
$view->setViewsDir('../app/views/');
return $view;
}, true);
$app->setDI($di);
$app->map('/', function () use ($app) {
echo $app['view']->render("index/index");
});
$app->map('/Page/Home', function () use ($app) {
if ($app->request->isAjax()) {
echo $app['view']->render("page/Home");
}
else{
//It means that the user is trying to access the page manually in the url input
//I would like to redirect him to my index page / page not found.
//But when I try to do it redirect me to the following url
// http://localhost/public/index/index
$app->response->redirect("index/index")->sendHeaders();
}
});
$app->notFound(function () use ($app) {
//Ajax "Page" request that is not found
if ($app->request->isAjax() && $app->request->isGet()) {
echo $app['view']->render("page/pageNotFound");
}
//Ajax "API" request that is not found
elseif ($app->request->isAjax() && $app->request->isPost()) {
$app->response->setStatusCode(400, "Bad Request");
$app->response->send();
}
//We render the index page, which will run the ajax call that will surely check
// if it's a real Page not found error.
else{
echo $app['view']->render("index/index");
}
});
$app->handle();
} catch(\Phalcon\Exception $e) {
echo "PhalconException: ", $e->getMessage();
}
最佳答案
//Setup a base URI so that all generated URI
$di->set('url', function () use ($di, $config) {
$url = new \Phalcon\Mvc\Url();
$dispatcher = $di->getShared('dispatcher');
$url->setBaseUri($config->url->baseUrl);
return $url;
});
之后你可以使用 url 服务来制作 URL
关于php - 如何使用 Phalcon php Micro 应用程序和自定义路由重定向到索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22444295/