使用匿名函数进行模板化并在PHP

时间:2017-06-04 12:06:25

标签: php anonymous-function output-buffering

我认为,在我审核代码时,我最好不要自欺欺人。

我正在建立一个网站,试图遵循MVC设计架构,虽然它甚至可能不是MVC但我觉得它很好用。

目前,我正在做这样的事情;

我有一个render()函数,它接受一个字符串$ template和参数数组

render($template, $vars=[]){
    extract($vars);
    ob_start();
    include($template.'.php');
    ob_flush();
}

并输出视图。在控制器中,我接着这样做,

Class WhicheverController

    public static function defaultAction(){
        $article=Article::getOneByID(array('id'=>$_GET['id'], 'user'=>User::currentUser()));  //returns database result as object
        render('_header', array('title'=>$article->title));
        render('header', array('user'=>User::currentUser()));
        render('sidebar', array('user'=>User::currentUser()));
        $content=Comment::getByArticleID(array('article'=>$article->id));  //returns object
        //of root comments, highest level in comment-replies tree
        $comments=function() use ($content){
            foreach($content as $comment){
                $threads[]=function() use ($comment){
                    render('comment', array('comment'=>$comment));
                }
            }
            render('pagination', array('content'=>$threads)); //pagination paginates based on number of
            //items in content, and echoes it or runs it if it is_callable
        }
        render('article', array('article'=>$article, 'comments'=>$comments));
    }

最后在article.php;

//some html with echoing $article->variablethis or variablethat
<div class="comments">
    <?= $comments(); ?>
</div>

现在,我想出来的方式,ob_flush()过早地发送给客户端,所以我得到样式和标题和侧边栏的标题打印,因为我得到了必要的变量。这很好(如果这是它的工作方式)。

然后,我想对主要内容 - 文章和评论做同样的事情。首先,我获得评论和文章数据,并将其传递给article.php。但是在发送它之前我必须首先做一些分页逻辑,这会延迟article.php的渲染。所以我创建了一个匿名函数,并将其作为变量函数传递给$ comments();在调用时它就是逻辑。

这只是一个例子。在一个控制器中,我首先获得今天,昨天和当前周的最高评价文章,并在将它们传递给frontpage.php之前为每个文章创建一个匿名函数。 Frontpage.php这样做,essentialy;

//some html markup
<?= $articles24h(); ?>
//more html
<?= $articles48h(); ?>
//and so on

现在,当我想到这一点时,我认为它很棒但是当我开始添加更多变量函数时,我注意到我的代码开始变得更长,我认为除了我以外的任何人都难以理解。

我的问题是:这是不好的做法;这种匿名函数,变量函数和ob_flush()的使用(更重要的是,它做了我认为它做的事情)?

编辑:代码本身有效。在这里,我可能犯了一些逻辑错误,但重点是显示函数的用法。

编辑2:好的,所以我意识到我可以有一个匿名函数显示 $articles24h$articles48h 任何分页内容,只需将每个分别传递给{{1像$content一样,这有很多帮助,但我仍然不知道这是否可取。即有更好的方法。

编辑3:我创建了3个View类,一个带有静态render()方法的View类,它只接受带有变量的模板名称和数组并打印出一个模板,还有另外两个,PaginationView和PartialView;两者都有自己的render()方法,并且不扩展View类(甚至认为如果我是一个更好的程序员yadda yadda,我会做不同的事情)。分页将PartialView存储在类变量中的部分视图分页,并在构造时创建。如果我不需要对数据进行分页,我只需要调用function($content) use ($something_else, $but_common){ //yada yada }

Neat(IMO),但在代码中看起来有点丑陋,如此:

PartialView->render()
然后将

$content=Article::getByAuthorID(array('author'=>$profile->id), array('order'=>$order,'column'=>'time_submitted')); $user_articles=new PartialView('_article', $content, array('length'=>60)); $user_articles=new PaginationView($user_articles->views, 10, 1); 发送到

$user_articles

正如您所看到的,我也这样做是为了评论所以代码变得冗长。我不想改变任何我没有破坏任何东西的东西,虽然我觉得这在某种程度上违反了DRY(?)

有没有更好的方法来做到这一点,而不是牺牲清晰度,但使其更紧凑?

0 个答案:

没有答案