شنبه یه خبراییه 🔥 منتظر شنبه باش 😉🥳
۰ ثانیه
۰ دقیقه
۰ ساعت
۰ محمدجوکار
نکته‌آموزشی: مثال برای Abstract Class و Interface
جامعه پی اچ پی ایجاد شده در ۲۰ دی ۱۴۰۱

عرض ادب و احترام.

چون دکتر آوند برای جلسات قبل، از مثال‌های پایگاه داده و کوئری‌ها استفاده کردند، شاید اگر یک مثال، در ادامه مباحث استاد، از این بخش ببینید، بهتر بتونید درک کنید.

اگر مشکل یا اشتباهی در کدها بود، خوشحال میشم بیان بفرمایید!

d709-Screenshot (587).png

/**********  we should create the interface first:  */
interface Queries
{
    public function select($pk$pkValue);
    public function update($key$value$pkValue);
    public function delete($pk$pkValue);
}
/**********  Then we can create BaseModel class and implement our interface:  */
abstract class BaseModel implements Queries
{
    /*** defining properties */
    protected object $db;
    protected string $table;
    protected string $primaryKey 'id';
   /***** Connection to Data Base */
    public function __construct()
    {
        try {
            $this->db = new PDO("mysql:dbname=dbName;hostname=localhost"'root''');
        } catch (PDOException $error) {
            die('there was an Error: ' . $error->getMessage());
        }
    }
    /***** defining Methods */
    public function select($pk$pkValue)
    {
        $query "SELECT * FROM {$this->table} WHERE {$pk} = :key";
        $stmt $this->db->prepare($query);
        $stmt->execute([':key' => $pkValue]);
        return $stmt->fetch(PDO::FETCH_OBJ);
    }
    public function update($key$value$pkValue)
    {
        $query "UPDATE {$this->table} SET {$key} = :value WHERE {$this->primaryKey} = {$pkValue}";
        $stmt $this->db->prepare($query);
        $stmt->execute([':value' => $value]);
        return $stmt->rowCount();
    }
    public function delete($pk$pkValue)
    {
        $query "DELETE FROM {$this->table} WHERE {$pk} = :pkValue";
        $stmt $this->db->prepare($query);
        $stmt->execute([':pkValue' => $pkValue]);
        return $stmt->rowCount();
    }
    # abstract methods: 
    # create (signature)
    abstract protected function insert($example);
}
/**********  Created a class of BaseModel:  */
class User extends BaseModel {
    protected string $table 'users';
    # abstract methods: 
    # create (body)
    public function insert($example){
        # anything
    }
}
class Folder extends BaseModel {
    protected string $table 'folders';
    # abstract methods: 
    # create (body)
    public function insert($example){
        # anything
    }
}
$test new User();
$result $test->select('id'1); 
var_dump($result) ;