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



假设我的用户类型为"Teacher",并且我有一个显示所有"Teachers"的列表页面。如何做最好?我有以下内容:

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

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

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

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中如何使用这些模型来了解更多关于这个概念的信息。

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

最新更新