このクラスを見て、私はアプリの外にあるコードは何をするべきかをほとんど知らないことを知っていますが、基本的にやるべきことが理解されていると思います。PHP - 静的メソッドを使用するかどうかをDBからロード/削除しますか?
<?php
class Customer
{
const DB_TABLE = 'customers';
public $id = NULL;
//all other properties here
function __construct($associative_array = NULL)
{
//fills object properties using values provided by associative array
}
static function load($customer_id)
{
$obj = new static(); //PHP 5.3 we use static just in case someone in future wants to overide this in an inherited class
//here we would load data from DB_TABLE and fill the $obj
return $obj;
}
static function delete($customer_id)
{
//here we just delete the row in the DB_TABLE based on $customer_id (which is the primary key of the table)
}
function save()
{
//saves $this properties into a row of DB_TABLE by either updating existing or inserting new one
}
}
(いつでも歓迎されている)を使用すると、コードになるだろうコメントの任意のタイプのほかに、ここでの主な質問は次のとおりです。「static
方法ですどのように悪いについてそんなに周りのSO上を読んだ、と使用static
の一般的なコードでは、このコードで2つの方法を静的ではないでしょうか?もしそうなら、小さな例で説明することができます。
$obj = new Customer(); //creating empty object
$obj->load(67); //loading customer with id = 67
の代わりに、単に
をやって:彼らに、私はそれがすべての時間を書くことを余儀なくされるDBからロードされた新しいオブジェクトを作成するために、奇妙なことだと思うstatic
原因をしないように私には奇妙に思えます
$obj = Customer::load(67); //creates a new customer and loads data form DB
「static」と宣言していないという削除についてお話しましょう。あなたのコードを使っているなら、私はこうします: '$ obj = getCar(78); $ obj-> delete(); 'これは' id = 78'の行をDBで削除すると思いますが、削除後に '$ obj'には何が入っていますか?例えば、私が '$ obj-> save();'を呼び出すと何が起こるのでしょうか? –
@MarcoDemaio私は通常オブジェクトにRESET関数を持っており、リセットはLOAD/DELETEで呼び出されます。したがって、オブジェクトはまったく新しいインスタンスになります。私はそれが必ずしも最良の方法ではないと言ったように、私はそれが好きです –