Laravel - 使用控制器而不是路由进行操作

时间:2013-01-10 21:47:37

标签: php laravel

我今天已经完全下载了Laravel,并且喜欢看起来很糟糕,但是我对两件事情进行了抨击。

1)我喜欢控制器分析网址而不是使用路由的动作方法,它似乎可以更清晰地将所有内容保持在一起,但是我想说要转到

/account/account-year/

如何为此编写动作功能?即

function action_account-year()...

显然不是有效的语法。

2)如果我有

function action_account_year( $year, $month ) { ...

并访问

/account/account_year/

将显示有关缺少参数的错误,如何使此用户友好/加载差异页/显示错误?

3 个答案:

答案 0 :(得分:8)

您必须手动路由连字符版本,例如

Route::get('account/account-year', 'account@account_year');

关于参数,它取决于您的路由方式。您必须接受路线中的参数。如果您使用完整控制器路由(例如Route::controller('account')),则该方法将自动传递参数。

如果您手动路由,则必须捕获参数

Route::get('account/account-year/(:num)/(:num)', 'account@account_year');

因此访问/account/account-year/1/2->account_year(1, 2)

希望这有帮助。

答案 1 :(得分:4)

您也可以考虑以下可能性

class AccountController extends BaseController {

    public function getIndex()
    {
        //
    }

    public function getAccountYear()
    {
        //
    }

}

现在只需按以下方式在路径文件中定义RESTful控制器

Route::controller('account', 'AccountController');

访问'account/account-year'将自动转到操作getAccountYear

答案 2 :(得分:0)

我想我会把这个作为答案添加,以防其他人在寻找它:

1)

public function action_account_year($name = false, $place = false ) { 
     if( ... ) { 
             return View::make('page.error' ); 
     }
}

2)

还不是一个可靠的解决方案:

laravel / routing / controller.php,方法“响应”

public function response($method, $parameters = array())
{
    // The developer may mark the controller as being "RESTful" which
    // indicates that the controller actions are prefixed with the
    // HTTP verb they respond to rather than the word "action".

    $method = preg_replace( "#\-+#", "_", $method );            

    if ($this->restful)
    {
        $action = strtolower(Request::method()).'_'.$method;
    }
    else
    {
        $action = "action_{$method}";
    }

    $response = call_user_func_array(array($this, $action), $parameters);

    // If the controller has specified a layout view the response
    // returned by the controller method will be bound to that
    // view and the layout will be considered the response.
    if (is_null($response) and ! is_null($this->layout))
    {
        $response = $this->layout;
    }

    return $response;
}