我最终创建了一个所有视图演示者都可以扩展的基类,并将其中的所有东西都移动到那里。在没有模型的视图上需要的函数我简单地添加为静态。
模型,我加了$presenterInfo
来传递信息加载正确的视图并用作标题前缀。视图演示者需要其余部分。
use Laracasts\Presenter\PresentableTrait;
...
use PresentableTrait;
protected $presenter = 'ArticlePresenter';
public $presenterInfo = ['view' =>'articles', 'category' => 'Article'];
基类,一切通用放在这里。因此,基本上所有可能对多个课程和他们的观点有用的东西。
use Laracasts\Presenter\Presenter;
class BasePresenter extends Presenter {
public static function pageHeader($level, $title, $small = null)
{
if ($small != null) $title .= " <small>" . $small . "</small>";
$html = "<div class=\"page-header\" style=\"margin-top: 0px\"><h%1\$d>$this->presenterInfo['category']: %2\$s</h%1\$d></div>";
return sprintf($html, $level, $title);
}
public function url()
{
return URL::route($this->presenterInfo['view'] . '.show', array('id' => $this->id, 'slug' => Str::slug($this->title)));
}
}
viewClass类,函数将只可用于所选择的类;在这种情况下为Article
。
class ArticlePresenter extends BasePresenter {
// Example function only needed by the article class.
public function stump()
{
return Str::limit($this->content, 500);
}
}
例子,加载视图主持人数据:
// Show page header level 2
{{ BasePresenter::pageHeader(2, 'Articles') }}
// Enumerate the articles and show title, stump and read more link
@foreach($articles as $article)
<article>
<h3>{{ HTML::link($article->present()->url, $article->title) }}</h3>
<div class="body">
<p>{{ $article->present()->stump }}</p>
<p><a href="{{ $article->present()->url }}">Read more...</a>
</div>
</article>
@endforeach
你能为你的通用视图逻辑的用例/例子吗?在何处/如何使用它们以及它们与您参考的图书馆有何不同 – JofryHS 2014-09-01 21:39:41
更新了示例通用视图逻辑和与视图展示器库不同的问题。 – 2014-09-01 21:45:35
那么使用Laravel的View Composer怎么样? http://laravel.com/docs/responses#view-composers您可以传递您正在使用的刀片模板(或布局基础),以确保每次都调用作曲者,并将变量传递给模板。 – JofryHS 2014-09-01 22:29:25