2017-01-06 3 views
0

「Teacher」というユーザータイプがあり、「Teachers」をすべて表示するリストページがあります。これを行うにはどうすればベストでしょうか?私は、次があります。単数とリストのコントローラを分けていますか?

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

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

を、私の単数ページは次のようになります。

$teachers = new Teachers; 

$all = $teachers->getTeachers(); 

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

と私の単数ビーイング:に比べ

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

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

本質的には、リスティングと単数型のコントローラ/モデルを別々に用意するのか、それとも1つのモデルに組み込むべきですか?

答えて

0

Teacherというモデルがあります。このモデルを使用して、すべてのまたは1人の教師を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でどのように使われているかを見ることができます。

モデルを作成して使用する方法についての最小限の例を示しましたが、この考え方でもっと多くのことを試すことができます。

+0

ありがとう、私たちのシステムでは、あなたの標準的なMVCパターンと少し異なります。私たちはカスタムcmsのバックエンド「モデル」とフロントエンドの「コントローラ」を持っています。 これで解決しました:) –

関連する問題