从视图到模型的变量。 MVC

时间:2014-10-11 21:34:48

标签: php mysql

我是初学者并根据教程JREAM(MVC)编写了一个网页。 我在展示文章时遇到了问题 如何从控制器向模型发送变量 $ (index.php)?
当然,我可以在index.php中连接数据库,但这是否合适?

的index.php     

    $limit = LIMIT; // article per page
    $article = $this->Ile[0]['num']; // number of articles 

    if (isset($_GET['page'])){
        $page = $_GET['page'];
    } else {
        $page = 1;
    }

    $allpage = round($article/$limit);
    $from = $limit * ($page - 1);

    // $from send value to model and model return array with article

    foreach($this->Article as $key => $value)
    {
        echo '<div style="float:left;width:660px;"><hr/><br/><p><span class="strong" style="color:#CC0000;">';
        echo $value['title'];
        echo '</span></p><br/><p>';
        echo $value['content'];
        echo '</p><div style="height:130px;">';
        echo $value['photo'];
        echo '</div></div>';
    }                   
    echo '<hr/>';
    echo '<div style="width: 660px; position: relative; pointer-events: none; text-align: center; top: 14px;">'.$page.' z '.$allpage.'</div>';

    if ($page == 1 && $page < $allpage)
    {
        echo '<a href="news?page='.($page+1).'" style="float: right;">STARSZE >></a>';
    }
    elseif ($page >= $allpage)
    {
        echo '<a href="news?page='.($page-1).'" style="float: left;"><< NOWSZE</a>';
    } else {
        echo '<a href="news?page='.($page-1).'" style="float: left;"><< NOWSZE</a>';
        echo '<a href="news?page='.($page+1).'" style="float: right;">STARSZE >></a>';
    }
?>

news.php

 class News extends Controller {

   function __construct() 
   {
     parent::__construct();
   }

   function index() 
   {
     $this->view->title = 'News';
     $this->view->Ile = $this->model->Ile();
     $this->view->Article = $this->model->Article();
     // I can put some value in ...->Article(0); and it works, but how connect in index.php

     $this->view->render('header');
     $this->view->render('news/index');
     $this->view->render('footer');
   }

 }

news_model.php

<?php

  class News_Model extends Model
  {
    public function __construct()
    {
      parent::__construct();
    }

    public function Ile()
    {
      return $this->db->select('SELECT COUNT(*) as num FROM `articles`');
    }

    public function Article($from)
    {
      return $this->db->select('SELECT * FROM `articles` ORDER BY `newsid` DESC LIMIT  '.$from.', '.LIMIT.'');
    }

  }

的问候,
 托马斯

1 个答案:

答案 0 :(得分:1)

您应该在控制器中不在视图中执行此操作:

控制器:

$limit = LIMIT; // article per page
$article = $this->view->Ile[0]['num']; // number of articles 

if (isset($_GET['page'])){
    $page = $_GET['page'];
} else {
    $page = 1;
}

$allpage = round($article/$limit);
$from = $limit * ($page - 1);
$this->view->Article = $this->model->Article($form); // This is how you can pass $form to model

然后您可以将此变量分配给您的视图,如:

$this->view->page = $page
$this->view->allpage = $allpage

现在您可以使用$ this-&gt;页面而不是$ page,同样适用于$ allpage

希望有所帮助