2014-09-01 36 views
0

我目前使用laracasts/Presenter来处理与我的视图相关的逻辑,此实现与模型相关。但是我也想要实现一些通用视图逻辑,创建它的最佳实践是什么?如何在Laravel中实现通用视图演示器

我已经尝试了两种方法,但也觉得不对劲:

  • 自定义类ViewHelper静态函数,调用ViewHelper::Method
  • 刀片包括文件,调用@include('includes.navicon')

是否有这样做的更好的办法?或者上述的一个(或两个)是可接受的?

编辑:我们在这里谈论简单的东西,像插入页面标题,通过Markdown解析器运行文本。这是我在所有页面上使用的函数的一个例子,它只是创建并返回一个页面标题。

public static function PageTitle($level, $title, $small = null) 
{ 
    if ($small != null) $title = $title . " <small>" . $small . "</small>"; 

    $html = "<div class=\"page-header\" style=\"margin-top: 0px\"><h%1\$d>%2\$s</h%1\$d></div>"; 
    return sprintf($html, $level, $title); 
} 

,我已经安装了该视图演示者使用该模式,因此要获得一个格式化的URL,例如我会用命令:{{ $article->present()->url }},而通用视图逻辑应当在所有视图中使用,而不必将其添加到所有模型。

+0

你能为你的通用视图逻辑的用例/例子吗?在何处/如何使用它们以及它们与您参考的图书馆有何不同 – JofryHS 2014-09-01 21:39:41

+0

更新了示例通用视图逻辑和与视图展示器库不同的问题。 – 2014-09-01 21:45:35

+0

那么使用Laravel的View Composer怎么样? http://laravel.com/docs/responses#view-composers您可以传递您正在使用的刀片模板(或布局基础),以确保每次都调用作曲者,并将变量传递给模板。 – JofryHS 2014-09-01 22:29:25

回答

0

我最终创建了一个所有视图演示者都可以扩展的基类,并将其中的所有东西都移动到那里。在没有模型的视图上需要的函数我简单地添加为静态。

模型,我加了$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