我能“返回”吗?两个对象从一个类我的路由发送到我的树枝模板


Am I able to "return" two objects from a class for my route to send to my twig template?

我是PHP微框架的新手,也是小模板系统的新手。

我想知道是否有任何方法从PHP函数"返回"两个对象,以便我的文章不需要两个函数(例如:getArticle, getComments) ?

我知道有一种方法可以用数组做到这一点,但有像我想做的对象吗?见下文.

当前类:

<?php
public function getArticle($id){
        $stmt = $this->app->engine->rows('SELECT null FROM articles WHERE id = :id', [':id' => $id]);
        if($stmt > 0){
            return $this->app->engine->testing('SELECT * FROM articles WHERE id = :id', [':id' => $id]);
        }else{
            return false;
        }
}
?>

我想达到的目标:

<?php
public function getArticle($id){
        $stmt = $this->app->engine->rows('SELECT null FROM articles WHERE id = :id', [':id' => $id]);
        if($stmt > 0){
            $article = new stdClass();
            $article->main = $this->app->engine->testing('SELECT * FROM articles WHERE id = :id', [':id' => $id]);
            $article->comments = $this->app->engine->testing('SELECT * FROM articles_comments WHERE article_id = :id', [':id' => $id]);
            return 'both of the above to $article of route';
        }else{
            return false;
        }
}
?>

路线:

<?php
$app->get('/articles/:id', function ($id) use ($app) {
        $article = new stdClass();
        $article = $app->user->getArticle($id);
        $article->comments = $app->user->getComments($id);
        $app->render('article.html', ['article' => $article]);
});
?>

我想达到的目标:

<?php
$app->get('/articles/:id', function ($id) use ($app) {
        $article = $app->user->getArticle($id);
        $article->main = 'use the returned $article->main';
        $article->comments = 'use the returned $article->comments';
        $app->render('article.html', ['article' => $article]);
});
?>

枝模板:

{{ article.main.title }}
{{ article.comments.message }}

你没有两个对象,你有一个对象$article,它有两个属性。只有return $article;,它将具有$article->main$article->comments的性质:

$article = new stdClass();
$article->main = $this->app->engine->testing('SELECT * FROM articles WHERE id = :id', [':id' => $id]);
$article->comments = $this->app->engine->testing('SELECT * FROM articles_comments WHERE article_id = :id', [':id' => $id]);
return $article;

:

$article = $app->user->getArticle($id);
// print_r($article);
// $article->main and $article->comments are already part of $article
$app->render('article.html', ['article' => $article]);