我想我在控制器中放了太多的代码,应该放在模型中。
这是我的控制器的一部分,我不会粘贴所有内容,因为有很多代码。
public function ajaxUsers() {
if($_GET["action"] == "listUsers") {
if(!isset($_POST["search"])) {
$this->_data['Records'] = $this->_model->getUsers();
$this->_data['Result'] = "OK";
$this->_data['TotalRecordCount'] = $this->_model->countUsers();
}
else {
foreach($_POST['fields'][0] as $key => $post) {
if ($post != "" && $key != "reg_date") {
$searchTerms = explode(' ', $post);
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$like[] = $key." LIKE '%".trim($term, '\'')."%'";
}
}
}
else if ($post != "" && $key == "reg_date") {
foreach ($post[0] as $key2 => $date) {
$datetofrom = strtotime($date);
$datetofrom = date('Y-m-d', $datetofrom);
if ($date != "" && $key2 == "datefrom") {
$like[] = "DATE_FORMAT(".$key.", '%Y-%m-%d') >= '".$datetofrom."'";
}
if ($date != "" && $key2 == "dateto") {
$like[] = "DATE_FORMAT(".$key.", '%Y-%m-%d') <= '".$datetofrom."'";
}
}
}
}
($like) ? $where_clause = "WHERE ". implode(' AND ', $like) : $where_clause = "";
$this->_data['Records'] = $this->_model->filterUsers($where_clause);
$this->_data['Result'] = "OK";
$this->_data['TotalRecordCount'] = $this->_model->countfilterUsers($where_clause);
}
echo json_encode ($this->_data);
}
}
我的模型主要是数据库查询:
public function getUsers() {
$data = $this->_db->select("SELECT * FROM ".PREFIX."users" . $this->_sort);
return $data;
}
public function countUsers() {
$data = $this->_db->select("SELECT count(*) as id FROM ".PREFIX."users");
return $data[0]->id;
}
public function filterUsers($like_clause) {
$data = $this->_db->select("SELECT * FROM ".PREFIX."users " .$like_clause. $this->_sort);
return $data;
}
public function countFilterUsers($like_clause) {
$data = $this->_db->select("SELECT count(*) as id FROM ".PREFIX."users ".$like_clause);
return $data[0]->id;
}
我应该在模型中移动foreach循环吗?
答案 0 :(得分:3)
PHP MVC - 我的控制器太胖了吗?
是的,特别是因为它包含业务逻辑,因此没有关注点分离。原因是您没有正确实现模型。模型由数据映射器和域逻辑处理程序组成。带来数据映射器和域对象的东西称为服务
模型不是一个类。将模型称为类就像调用class MyLiskovSubstitionClass {}
一样。这是数据抽象的概念。模型由服务组成。
为了正确实现它,你要从编写映射器开始:
class UserMapper
{
public function getUsers()
{
$data = $this->_db->select("SELECT * FROM ".PREFIX."users" . $this->_sort);
return $data;
}
// ... The rest what abstracts table access
}
然后你会写一个名为UserManager
final class UserManager
{
private $userMapper;
public function __construct($userMapper)
{
$this->userMapper = $userMapper;
}
public function search(array $input)
{
$data = array();
if (!isset($input["search"])) {
$data['Records'] = $this->userMapper->getUsers();
$data['Result'] = "OK";
$data['TotalRecordCount'] = $this->userMapper->countUsers();
// Do the rest
}
return $data;
}
}
最后:
public function ajaxUsers()
{
if ($_GET["action"] == "listUsers") {
$result = $this->userManager->search($_POST);
die(jscon_encode($result));
}
}