【问题标题】:How can I call a controller method in a view or another controller?如何在视图或另一个控制器中调用控制器方法?
【发布时间】:2010-10-15 08:42:36
【问题描述】:

我有主控制器,打印主页。

<?

class Main extends Controller {

    function Main()
    {
        parent::Controller();

        $this -> load -> helper('date');
    }

    function index()
    {
        $this -> load -> view('header');
        $this -> load -> view('main');
        $this -> load -> view('footer');
    }
}

?>

我有文章控制器,打印最后 6 篇文章。

<?php

class Articles extends Controller
{
    function Articles()
    {
        parent::Controller();
    }

    function top()
    {
        $this -> db -> limit(0, 6);
        $query = $this -> db -> get('articles');

        $data['articles'] = $query -> result();

        $this -> load -> view('articles-top', $data);
    }

?>

标题视图如下所示:

<html>
    <head>
    ...
    </head>
    <body>

        <div id="last-articles">
            <!-- Here I want print last 6 articles -->
        </div>

        <div id="content">

如何在标题视图中打印最后一篇文章?

【问题讨论】:

  • 看起来像 CI 代码,而不是 Kohana
  • 我已将其重新标记为 Codeigniter。 Kohana 已经很久没有 $this->load->... 了。

标签: php codeigniter controller


【解决方案1】:

$data 数组中的数组键成为视图中的变量。

Code Igniter User Guide 非常有用。

你可以在你的视图中做这样的事情:

<html>
<head>
...
</head>
<body>

    <div id="last-articles">
        <?php 
            foreach($articles as $article)
            {
                echo $article.title;    //obviously these would be the real fields
                echo $article.content;  //from your article table.
            }
        ?>
    </div>

    <div id="content">

【讨论】:

    【解决方案2】:

    你做错了。

    你的控制器需要有这样命名的函数...

    public function action_youractionname($value='')
    {
       $array_of_data_for_view = array( 'data' => $some values );
       echo View::factory( 'viewfilename', $array_of_data_for_view )->render();
    }
    

    您的视图可以使用 $data 变量。

    希望这会有所帮助,但我会推荐这个网站.. http://kerkness.ca/wiki/doku.php

    这对我来说是无价的。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多