Laravel中的控制器和路由

时间:2016-10-18 11:26:39

标签: laravel

Controller和Routes之间的区别基本上是什么。我们可以使用routes文件控制我们的数据,那么为什么我们需要控制器?

喜欢:

<?php 
// app/routes.php
// route to process the ducks form
Route::post('ducks', function()
{

// process the form here

// create the validation rules ------------------------
$rules = array(
    'name'             => 'required',                        // just a normal required validation
    'email'            => 'required|email|unique:ducks',     // required and must be unique in the ducks table
    'password'         => 'required',
    'password_confirm' => 'required|same:password'           // required and has to match the password field
);

// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);

// check if the validator failed -----------------------
if ($validator->fails()) {

    // get the error messages from the validator
    $messages = $validator->messages();

    // redirect our user back to the form with the errors from the validator
    return Redirect::to('ducks')
        ->withErrors($validator);

} else {
    // validation successful ---------------------------

    // our duck has passed all tests!
    // let him enter the database

    // create the data for our duck
    $duck = new Duck;
    $duck->name     = Input::get('name');
    $duck->email    = Input::get('email');
    $duck->password = Hash::make(Input::get('password'));

    // save our duck
    $duck->save();

    // redirect ----------------------------------------
    // redirect our user back to the form so they can do it all over again
    return Redirect::to('ducks');

}

});

嗯,这不是我的代码,我在某处读过它,但是,这里的人已经在routes.php文件中使用了验证,在我的项目中,我在一个名为UserController的控制器中使用了验证技术,这有什么区别呢它呢?

3 个答案:

答案 0 :(得分:2)

路由将每个传入的HTTP请求转换为操作调用,例如转换为控制器的方法,而 controller 是写入业务逻辑的位置。在一个文件中处理所有文件没有任何问题,但是一旦你的项目变得更大,管理这样的代码将是一场噩梦。它就像责任,路由,路由,路由请求到特定控制器,控制器处理它,传递结果查看。主要是它的设计模式。

答案 1 :(得分:2)

我们甚至可以将所有代码放在一个巨大的文件中而不使用任何类,但我们知道这不是一个好主意。当前的最佳实践是根据职责(单一责任原则)分离代码,以便其他开发人员更容易阅读和理解代码。通常下一个开发人员在几个月内就是你自己,所以拥有一个干净的结构不仅对其他人有益,而且在回到原来的代码时也是你的理智。

路由器名称意味着类路由数据,在这种情况下从URI到控制器,控制器处理该特定控制器的业务规则

答案 2 :(得分:0)

laravel中的路由是您定义应用程序端点的位置,控制器是您编写业务逻辑的位置。

当我开始学习并简化Laravel时,我遇到了同样的问题,我已经创建了一些MCV风格的项目请检查

https://github.com/jagadeshanh/understanding-laravel

相关问题