Yii2在beforeAction方法

时间:2016-04-12 11:06:10

标签: yii2

我有一个扩展Controller的MainController。我的所有应用程序的控制器都从MainController扩展而来,其中包括需要从任何Controller访问的各种方法和属性。

在我的MainController中是beforeAction,它做了几件事:

  • 检查数据库中保留的重定向,如果URL与数据库中的URL匹配,则执行重定向。
  • 为每个控制器生成<head>数据
  • 根据网址的Cookie和slug获取用户正在查看的语言和国家/地区。 (即http://example.com/netherlands)。
  • 如果URL与数据库的pages表中的一个匹配,则会从模板中呈现通用页面。

这是我最后一次挣扎。在我的MainController中我有这个:

/**
* Before action, check all $this->before_actions satisfy. If no head_data provided, try and fill in some basics
*/
public function beforeAction( $action )
{

    // Run parent method first
    if (!parent::beforeAction($action))
        return false;

    // Check redirects
    $this->checkRedirects();

    if( $this->checkPages() )
    {

        // If not error page, loop through before methods
        if( $action->id !== 'error' )
        {

            // Loop through actions to peform and do them
            foreach ( $this->before_actions as $before_method )
                $this->$before_method();
        }
        return true;
    }

}

其中$ this-&gt; checkPages()包含以下内容:

/**
* Check for pages
*/
public function checkPages()
{

    // Attempt to find page for this request
    $page = Page::find()->where( [ 'permalink' => trim( str_replace( getBaseUrl() , "", getCurrentUrl() ), "/" ) ] )->one();

    // If found, load it instead
    if( !empty( $page ) )
        return Yii::$app->runAction( "pages/show", [ 'id' => $page->id ] );

    // Else, return
    return true;

}

我遇到的问题是,如果我转到http://example.com/story,因为没有StoryController,虽然动作确实运行并且输出了视图“views / story / show”,但会返回404错误。 / p>

我该如何防止这种情况?

编辑:

要添加,日志显示它首先说: "Unable to resolve the request 'story/index'"

但是其他日志显示: "Route to run: pages/show" ... "Running action: app\controllers\PagesController::actionShow()" .. Rendering view file: /Users/stefandunn/Documents/Local Machine Development/views/pages/show.php

所以我猜这是导致404状态的第一个日志结果

1 个答案:

答案 0 :(得分:0)

添加最后一条可以捕获任何模式并重定向到自定义操作的路由。

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        //...
        '<any:.*>' => 'site/index' 
    ],
],
相关问题