1

PHP プロジェクトを OOP に再コーディングし始めました。多くの中でうまくいかないことの1つは、動的な選択リストを作成する方法です。作成する検索選択リストがたくさんあります。それについて行く最善の方法は何ですか?

すべての汎用データベース クエリを含む DatabaseObject クラスを作成しました。それらをここに追加するか、それとも特別なクラスを作成する必要がありますか? また、それをコーディングするにはどうすればよいですか?

require_once("database.php");

class DatabaseObject {

protected static $table_name;

// find all from a specific table
public static function find_all(){      
    global $database;
    return static::find_by_sql("SELECT * FROM ".static::$table_name);       
}

// select all from a specific table
public static function find_all_from($table){       
    global $database;
    return static::find_by_sql("SELECT * FROM " .$table);       
}

// find all from a specific table
public static function find_by_id($id){

    global $database;
    $result_array = static::find_by_sql("
    SELECT * FROM ".static::$table_name. " WHERE id = '{$id}' LIMIT 1");

    // return the data only for the one user
    return !empty($result_array) ? array_shift($result_array) : false;      
}

// find using sql
public static function find_by_sql($sql=""){

    global $database;
    // return all data from sql
    $result_set = $database->query($sql);
    $object_array = array();
    while($row = $database->fetch_array($result_set)){
        $object_array[] = static::instantiate($row);    
    }
    return $object_array;       
}


protected static function instantiate($record){

    $class_name = get_called_class();
    $object = new $class_name;

    foreach($record as $attribute=>$value){
        if($object->has_attribute($attribute)){
            $object->$attribute = $value;
        }
    }
    return $object;
}


protected function has_attribute($attribute){

$object_vars =  $this->attributes();

// here we only want to know if the key exist
// so we will return true or false
return array_key_exists($attribute, $object_vars);      
}

protected function attributes() {

$attributes = array();
foreach(static::$db_fields as $field) {
    if(property_exists($this,$field)) {
    $attributes[$field]= $this->$field; 
    }
}
return $attributes; 
}

protected function sanitised_attributes() {
global $database;
$clean_attributes = array();
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);  
}
return $clean_attributes;   
}


public function save() {
// A new object won't have an id yet
return isset($this->id) ? $this->update() : $this->create();
}

// create new  
protected function create() {
global $database;
$attributes =$this->sanitised_attributes();

$sql  = "INSERT INTO ".static::$table_name." (";
$sql .= join(", " ,array_keys($attributes));
$sql .= ") VALUES ( '";
$sql .= join("', '" ,array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
    $this->id = $database->insert_id();
    return true;
} else {
    return false;
}
}

// update details
protected function update() {
global $database;
$attributes =$this->sanitised_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
    $attribute_pairs[] = "{$key}='{$value}'";   
}
$sql  = "UPDATE " .static::$table_name. " SET ";    
$sql .= join(", ",$attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() ==1) ? true : false ;
}


public function delete() {
global $database;

$sql  = "DELETE FROM ".static::$table_name;
$sql .= " WHERE id =". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() ==1) ? true : false ;
}
}
4

4 に答える 4

1

カプセル化できる明確に定義された責任があるため、選択リストをオブジェクトとしてモデル化することは間違いありません。DatabaseObjectこれらのクラスのいずれかの変更が他のクラスに影響を与えないように、クラスから可能な限り分離したままにします。例として、次のことを考慮してください。

class SelectList
{
    protected $options;
    protected $name;

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

    public function render()
    {
        $html = "<select name='" . $this->name . "'>\n";
        foreach ($this->options as $option) 
        {
            $html .= $option->render();
        }
        $html .= "</select>\n";
        return $html;
    }
}

class SelectListOption
{
    protected $label;
    protected $value;
    protected $isSelected;

    public function __construct($label, $value, $isSelected = false)
    {
      //Assign the properties
    }

    public function render()
    {
        $html .= '<option value="' . $this->value . '"';
        if ($this->isSelected)
        {
         $html .= ' selected="selected" ';
        }
       $html .= '>' . $this->label . "</option>\n";
    }
}

この方法でモデル化することについて私が気に入っていることの 1 つは、新しい機能がどのオブジェクトに属しているかがわかるため、新しい機能 (選択/選択されていない項目の CSS スタイル、または無効な属性など) の追加が非常に簡単であることです。また、この種の「小さな」オブジェクトを使用すると、単体テストを非常に簡単に作成できます。

HTH

于 2012-11-05T13:38:20.827 に答える
0

メソッドに渡された連想配列を反復処理して、HTML 選択/オプション ビューを返すメソッドを作成するだけです...? このようなものかもしれません:

public static function viewSelect($name = "select", $arr_options = array()) {
    $html = "<select name='$name'>\n";
    foreach ($arr_options as $key => $val) {
        $html .= "<option value='$key'>$val</option>\n";
    }
    $html .= "</select>\n";
    return $html;
}

次に、データベース クエリの 1 つからの結果をこのメソッドに渡すだけです。このメソッドは、必要な適切なクラスに配置できます。

于 2012-11-04T17:50:15.823 に答える
0
public function get_posts()
{
    $query="select * from tbl_posts";
    $result=  mysql_query($query);
    $i=0;
    while($data=  mysql_fetch_assoc($result))
    {
        foreach($data as $key=>$value)
        {
            $info[$i][$key]=$value;
        }
        $i++;
    }
    return $info;


}
于 2013-03-28T16:48:01.267 に答える