在我看来,为什么Laravel用我的模型中的变量覆盖我在控制器中声明的变量


In my view, why does Laravel overwrite variables I declare in my controller with those from my model?

我对MVC设计模式的理解有误吗?为什么Laravel似乎覆盖了我在控制器中声明的变量,并用我的模型中的变量传递给我的视图?假设我将变量$journey从我的控制器传递到我的视图,如下所示:

class JourneyController extends BaseController {
    public function journey($id) {
        $journey = Journey::find($id);
        // I overwrite one of the attributes from the database here. 
        $journey->name = "Overwritten by the Controller";
        return View::make('journey', array(
            'journey' => $journey,
            'bodyClass' => 'article'
        ));
    }    
}

但是,我正在使用访问器修改Journey模型中的$journey->name属性:

class Journey extends Eloquent {
    protected $table = 'journeys';
    protected $primaryKey = 'id';
    public $timestamps = false;
    public function getNameAttribute($value) {
        return 'Overwritten by the Model';
    }
}

因此,当我的视图被创建时,我会像这样显示$journey->name

{{ $journey->name }}

我只剩下:

"Overwritten by the Model";

为什么会出现这种情况?控制器不是处理一个请求,从我的模型中获取信息,对其进行操作,然后将其传递到可以输出的视图吗?如果是这种情况,为什么,以及如何,模型似乎在两者之间"跳跃",用自己的变量覆盖我的控制器编写的变量?

我知道这是旧的,但我今天刚刚在Laravel 4.2上找到了一个解决方案。

class Journey extends Eloquent {
    protected $table = 'journeys';
    protected $primaryKey = 'id';
    public $timestamps = false;
    public function getNameAttribute($value = null) {
        if($value)
            return $value;
        return 'Overwritten by the Model';
    }
}

您应该如上所述更新getNameAttribute函数以返回设置值(如果有),而不是总是返回字符串。以前,调用这个值总是运行函数并忽略设置的值,但现在函数首先检查您设置的值。

希望两年还不算太晚,还能帮助一些人!

看看如何使用Presenters,Take Jeffery Way的Presenter Package。正常安装它,然后可以将$presenter变量添加到您的模型中。

例如:

use Laracasts'Presenter'PresentableTrait;
class Journey extends Eloquent {
    use PresentableTrait;
    protected $presenter = "JourneyPresenter";
}

然后您可以创建您的JourneyPresenter类:

class JourneyPresenter {
    public function journeyName()
    {
        return "Some Presentation Name";
    }
}

在你看来,你可以这样称呼它:

<h1>Hello, {{ $journey->present()->journeyName }}</h1>

它确实有助于将这种"演示"逻辑排除在视图和控制器之外。你应该尽量让你的控制器只用于它的预期目的,处理路线和基本保护,并减少你的视图逻辑。

至于你的问题,你可能只是在经历Laravel操作的自然顺序。