独立数据操作
大多数的控制器代码用来处理数据操作,但是你要是使用另一个控制器呢?!你难道不像将所有访问数据库的代码放到一个位置来避免代码重复?对了,从控制器中分离出这些代码到模型层
<?php
function getAllPosts() { // Connecting, selecting database $link = mysql_connect('localhost', 'myuser', 'mypassword'); mysql_select_db('blog_db', $link);
// Performing SQL query $result = mysql_query('SELECT date, title FROM post', $link);
// Filling up the array $posts = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $posts[] = $row; }
// Closing connection mysql_close($link);
return $posts; }
?> |
而控制层变为
<?php
// Requiring the model require_once('model.php');
// Retrieving the list of posts $posts = getAllPosts();
// Requiring the view require('view.php');
?> |
控制层变得很容易理解,他唯一的任务就是从模型中读取数据并传送与视图。在复杂应用中,控制层要处理请求、用户
Session
、授权等