用于单数和列表的独立控制器?

时间:2017-01-06 11:57:42

标签: php model-view-controller

假设我的用户类型为“教师”,并且我有一个显示所有“教师”的列表页面。怎么会这样做?我有以下内容:

$teachers = new Teachers;
$data = $teachers->getTeachers();

foreach($data as $teacher) {
    echo $teacher->name
}

我的单数页面将是:

$teacher = new Teacher('Jane Doe');
echo $teacher->name;

与:

相比
$teachers = new Teachers;

$all = $teachers->getTeachers();

foreach($all as $teacher) {
    echo $teacher->name;
}

和我的独特存在:

$teacher = $teachers->getTeacher('Jane Doe');
echo $teacher->name;

基本上,我应该为列表和单数设置单独的控制器/模型,还是将它们合并为一个?

1 个答案:

答案 0 :(得分:0)

您需要的是一个名为Teacher的模型,可用于从db获取所有或单个教师。当然,该模型也负责创建/更新/删除教师。

class Teacher { // this should extend a Model class which share common methods to all models

  public $id;
  public $name;

  public function __construct($id, $name)
  {
    $this->id = $id;
    $this->name = $name;
  }

  public static function find($id) // this is a common method
  {
    // query db to get the teacher with given ID
    // The results are assigned to $row variable

    return self::createFromArray($row);
  }

  public static function all()
  {
    // query db to get all the teachers

    $teachers = []; // instead of an array you can create a collection class which may have some useful methods

    foreach ($rows as $row) {
      $teachers[] = self::createFromArray($row);
    }

    return $teachers;
  }

  public static function get($attributes)
  {
    // you can build a query with where clause by given attributes (eg. if you want to search by name)
    // after getting the results you can use the same example as all() method
  }

  public static function createFromArray($fields) // this is a common method
  {
    return new self(...$fields); // ... operator since PHP 5.6
  }
}

在您的控制器中,您可以使用以下模型:

foreach (Teacher::all() as $teacher) {
    echo $teacher->name;
}

echo Teacher::find(1)->name; // echo the name of the teacher having ID 1

foreach (Teacher::get(['name' => 'John']) as $teacher) {
   echo $teacher->name;
}

这个例子的灵感来自Laravel。您可以看到如何在Laravel中使用模型来更多地了解这个概念。

我刚刚给你一个关于如何创建和使用模型的最小例子,但你可以尝试更多关于这个想法的事情。

相关问题