繁体   English   中英

如何使用Phalcon php Micro应用程序和自定义路由重定向到索引

[英]How to redirect to index using Phalcon php Micro application and custom routing

我正在使用Php和Phalcon框架构建一个Ajax驱动的Web应用程序。

当用户访问网站时,他的请求将在我的pageNotFound方法中处理,该方法将呈现index.php视图,此视图将调用我的服务器将Page前缀添加到当前URL以在div中加载HTML。

所以www.mywebsite.com/home将调用我的服务器www.mywebsite.com/Page/Home ,它将在div中呈现html。

我想将用户重定向到主页,如果他试图直接从其浏览器中的url输入访问Page 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;
});

在此之后,您可以使用网址服务来制作网址

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM