我遇到了一个问题,这似乎意味着我不了解Laravel中的架构是如何正确工作的。我是拉拉维尔的新手,但我以为我知道这一点。当客户端请求页面时,会调用一个控制器,该控制器从模型中提取数据并将其传递给视图。如果前面的说法是正确的,那么为什么会出现这个问题:
在我的JourneyController
:中
public function journey($id) {
// Find the journey and the images that are part of the journey from the db
$journey = Journey::find($id);
$imagesInJourney = Journey::find($id)->images->keyBy('id');
// Perform some manipulation on the article. THE ERROR OCCURS HERE.
$journey->article = str_replace('[[ ' . $image . ' ]]', $html, $journey->article);
return View::make('journey', array(
'journey' => $journey,
'title' => $journey->name,
'bodyClass' => 'article'
));
}
这个控制器被调用,并从我的Journey
模型中提取数据(如下)。特别是,我有一个属性,我称之为article
,在发送到我的控制器之前我正在操纵它:
class Journey extends Eloquent {
protected $table = 'journeys';
protected $primaryKey = 'id';
public $timestamps = false;
// Database relationship
public function images() {
return $this->hasMany('Image');
}
// THIS IS THE PROBLEMATIC METHOD
public function getArticleAttribute($value) {
return file_get_contents($value);
}
}
正如您所看到的,我正在编辑article
字段,它只是一个指向文件的链接,并使用PHP的file_get_contents()
函数将其替换为实际的文件内容。因此,我的理解是,当它返回到上面的Controller时,$journey->article
将包含文章本身,而不是它的URL。
然而,出于某种原因,我的控制器中的这句话,我用图像替换了文章文本的部分,导致了问题:
$journey->article = str_replace('[[ ' . $image . ' ]]', $html, $journey->article);
在我对journey.blade.php
的看法中,我试图输出$journey->article
,希望它是添加了图像的文章文本,但我收到了错误:
ErrorException (E_UNKNOWN) file_get_contents(*entire article content here*): failed to open stream: Invalid argument (View: app/views/journey.blade.php)
为什么当我尝试调用str_replace()
时会发生这种情况?如果我把它评论出来,效果会很好。
由于每次获取/回显该属性时都会调用getArticleAttribute方法,所以在第一次获取时没有问题(这是执行str_replace函数的地方),但当您再次尝试获取article属性时(这是在视图页中回显的地方)您已经更改了属性的值,因此您的函数尝试再次执行file_get_contents。
解决方案是在旅程类中有一个标志,并在执行file_get_contents时将其设置为true,并为其他调用返回属性本身。
喜欢;
class Journey extends Eloquent {
protected $table = 'journeys';
protected $primaryKey = 'id';
public $timestamps = false;
private $article_updated = false;
// Database relationship
public function images() {
return $this->hasMany('Image');
}
// THIS IS THE PROBLEMATIC METHOD
public function getArticleAttribute($value) {
if($this->article_updated){
return $value;
}
else {
$this->article_updated = true;
return file_get_contents($value);
}
}
}