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

时间:2014-03-16 23:03:50

标签: php redirect phalcon

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

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

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

如果用户试图直接从其浏览器中的网址输入访问Page网址,我想将用户重定向到主页。

但是当我尝试重定向他时,网址会变为: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();
}

1 个答案:

答案 0 :(得分:2)

//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;
});

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