【问题标题】:Separate controllers for singular and listing?单独的控制器和列表?
【发布时间】:2017-01-06 11:57:42
【问题描述】:

假设我的用户类型为“教师”,并且我有一个显示所有“教师”的列表页面。如何最好地做到这一点?我有以下内容:

$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;

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

【问题讨论】:

    标签: php model-view-controller


    【解决方案1】:

    您需要的是一个名为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 中如何使用这些模型来了解更多有关此概念的信息。

    我只是给你一个关于如何创建和使用模型的小例子,但是你可以围绕这个想法尝试更多的东西。

    【讨论】:

    • 谢谢,我们的系统与您的标准 MVC 模式略有不同。我们有一个用于自定义 cms 的后端“模型”和一个前端“控制器”。不过,这已经清除了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 2020-11-29
    • 2022-07-09
    相关资源
    最近更新 更多