【问题标题】:Phalcon router doesn't seem to be setPhalcon路由器似乎没有设置
【发布时间】:2016-03-18 09:26:29
【问题描述】:

我已经设置了自定义路由,我的 routes.php 目前看起来是这样的:

<?php
$router = new Phalcon\Mvc\Router();

$router->add('athlete/{username}', array(
    'controller' => 'athlete',
    'action' => 'index',
));

return $router;

在我的 services.php 中,我正在设置路由器:

$di->set('router', function() {
    return require __DIR__ . '/routes.php';
});

我的 AthleteController 的 index Action 看起来像这样,出于测试目的,我将参数传递给视图 (username):

public function indexAction()
{
    $username = $this->dispatcher->getParam('username');

    if (!isset($username)) {
        $user = Users::findFirstByUsername($this->auth->getIdentity()['username']);
    } else {
        $user = Users::findFirstByUsername($username);
        if (!$user) {
            $this->flash->error('Could not find this user');
        }
    }
    $this->view->user = $user;
    $this->view->username = $username;
    $this->view->setTemplateBefore('public');
}

当我不使用自定义参数时,它可以工作,它可以找到用户并显示他的用户名。但是,当我使用例如 url athlete/kerowan 时,我收到错误 Action 'kerowan' was not found on handler 'athlete',据我了解,这意味着路由器设置不正确或没有捕获 URL。有什么想法吗?

【问题讨论】:

    标签: php phalcon phalcon-routing


    【解决方案1】:

    前段时间我遇到了同样的问题,我在文档或论坛中的任何地方都找不到如何使用可选参数创建路由。如果我希望方法具有不同的行为(例如在您的示例中),我想出的最佳解决方案是有两条路线。这将为您解决问题:

    $router->add('/athlete/{username}', 'Athlete::index');
    $router->add('/athlete', 'Athlete::index');
    

    如果有人有更好/更优雅的解决方案,请分享:)

    【讨论】:

    • 再次感谢您:) 看起来很奇怪,因为在 Vokuro 示例应用程序中它似乎可以工作。但无论如何,这对我有用!
    【解决方案2】:

    默认情况下,phalcon 的路由器在此约定中使用自动路由:'/:module/:controller/:action/:params 在多模块应用程序中,'/:controller/:action/:params 在单模块应用程序中。如果你想摆脱它,那么你必须将 false 传递给路由器构造函数。

    【讨论】:

    • 嗯,vokuro 应用程序不会将 false 传递给路由器构造函数,它仍然适用于它们。
    • 你在 vokuro 中指的是什么动作和控制器?
    • 控制器:UserControl,操作:confirmEmail 和 resetPassword。实际上,这是在 vokuro routers.php 中路由的仅有的两个动作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    相关资源
    最近更新 更多