【问题标题】:Controller and Routes in LaravelLaravel 中的控制器和路由
【发布时间】:2017-02-27 15:40:42
【问题描述】:

Controller 和 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 的控制器中使用了验证技术,有什么区别它使?

【问题讨论】:

  • 享受将 100 个函数用于 100 种不同的事物放在一个文件中。控制器也是完全不同的东西,查一下。
  • 另外,如果你只有一个基于闭包的路由,你就不能使用路由缓存。

标签: laravel


【解决方案1】:

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

当我开始学习并使其变得简单时,我在理解 Laravel 时遇到了同样的问题,我创建了一些 MCV 风格的项目,请检查一下

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

【讨论】:

    【解决方案2】:

    Routes 将每个传入的 HTTP 请求转换为操作调用,例如转换为控制器的方法,而 controller 是编写业务逻辑的地方。在一个文件中处理所有内容并没有错,但是一旦您的项目变得更大,管理此类代码将是一场噩梦。这就像责任,路由,将请求路由到特定的控制器,控制器处理它,将结果传递给视图。主要是设计模式。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2023-03-27
        • 2017-03-05
        • 2014-08-20
        • 1970-01-01
        • 1970-01-01
        • 2014-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多