簡體   English   中英

如何在OO PHP中編碼?

[英]How to code in OO PHP?

如何在OO PHP中執行此操作:

  1. 表格(在newstudent.php中)要求用戶輸入其姓名,課程和年份。
  2. 選擇“提交”按鈕后,頁面將轉到“ records.php” records.php-包含一個顯示所有記錄的表(列:名稱,課程,年份)
  3. 當用戶選擇“提交”時,新記錄將添加到具有名為STUDENTS的表的數據庫中

SQL代碼

CREATE TABLE STUDENTS(
   NAME VARCHAR(25) NOT NULL,
   COURSE VARCHAR(25) NOT NULL,
   YEAR INT NOT NULL,
CONSTRAINT STUDENTS_PK PRIMARY KEY(NAME));

*請不要介意主鍵,因為我知道將名稱用作主鍵並不准確。 這只是出於示例目的。

還有...我如何使用OO PHP處理DB中的數據? 謝謝

  1. 讀一本書
  2. 搜索谷歌
  3. 創建學生對象
  4. 創建數據庫對象
  5. 查詢數據庫對象以插入學生對象

好吧,如果您要切換為在數據庫中表示學生的OO方法,那么看起來類似於以下定義的“學生”類又如何(盡管這是非常基本的,而且絕不是完整的ORM)。 它將您帶到ActiveRecord樣式方法的一半。

請注意,我假設您將使用整數id列,否則將使整個類煩人。

class Student {

   var $id = -1;
   var $name;
   var $course;
   var $year; 

   public static function newFromID ($id) 
   {
     //fetch a row ($row) from the students table matching the given id
     //perhaps returning false if the student doesn't exist?
     return self::newFromRow($row);
   }

   // this method should return a new student object given a specific db row
   // and should be called from newFromID.  This function means that if the table
   // changes, modifications only have to be made in one place
   public static function newFromRow($row) 
   {
     $obj = new Student();

     //fill in the fields of the object based on the content of the row

     return $obj;
   }

   public static function getAllStudents()
   {
     //perhaps return an array of student objects, by doing a broad select,
     //and passing each row to newFromRow?
   }

   //this should save the object to the database, either inserting or updating as appropriate
   public function save()
   {
     if($this->id == -1) 
     {
        //insert, store the auto_increment id in $this->id
     } else {
        //update
     }

   }

}

因此,要創建一個新學生並將其保存到數據庫中:

$student = new Student();

$student->name = "John Smith";
$student->course = "French";
$student->year = 2;

$student->save();

實際上,使用現有的ORM系統通常更明智,但是如果這不是一種選擇,則可以考慮編寫自己的ORM系統。

也許您在談論ORM-對象關系映射模式? 有許多不同的方法可將SQL數據對象映射到PHP類:Propel,Doctrine(均可與Symfony框架一起使用),ActiveRecord。

當然,您可以嘗試實現自己的ORM系統。 您需要為此ORM編寫數據訪問層,描述SQL表和許多其他內容的類。 這是非常有趣的(出於教育目的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM