جشنواره عیدانه راکت | عضویت ویژه راکت برای آخرین بار | افزایش قیمت‌ها از سال جدید | و ...

مشاهده اطلاعات بیشتر...
ثانیه
دقیقه
ساعت
روز
tarane haghparast
3 سال پیش توسط tarane haghparast مطرح شد
1 پاسخ

کنترلر مشترک برای عملیات crud تکراری

سلام دوستان نظرتان راجع به DRY principle with CRUD Views چیه؟
اینکه یک کنترلر پایه برای عملیات crud همه مدل ها ایجاد کنیم که از تکرار جلوگیری شه


ثبت پرسش جدید
امیر حسین
تخصص : وردپرس کار
@kalanamir815 1 سال پیش مطرح شد
0

سلام، بنظرم این کلاس بتونه بهت کمک بنه

class database
{
    private $dsn = "mysql:host=localhost";
    private $username = 'root';
    private $password = 'root';
    private $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_CASE => PDO::CASE_NATURAL,
        PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
    ];
    public $conn;

    public function insert(string $table, array $feilds , $values) : bool
    {
        $count = count($feilds);
        $prepare_repeat = chop(str_repeat('?,',$count),',');
        $feilds = implode(',',$feilds);
        $stmt = $this->conn->prepare("insert into $table ($feilds) values ($prepare_repeat)");
        $result = $stmt->execute($values);
        return $result;
    }

    public function update(string $table, array $feilds, array $values, string $where_conditional,array $where_value) : bool
    {
        $feilds = array_map(fn($item)=>"$item = ? ,",$feilds);
        $feilds = chop(implode('',$feilds),',');
        $feilds = chop($feilds,',');
        $where_value = array_map(fn($item)=>"'$item'",$where_value);
        $where_value = implode(',',$where_value);
        $stmt = $this->conn->prepare("update $table set $feilds where $where_conditional = $where_value");
        $result = $stmt->execute($values);
        return $result;
    }

    public function delete(string $table, string $where_conditional,array $where_value) : bool
    {
        $where_value = array_map(fn($item)=>"'$item'",$where_value);
        $where_value = implode(',',$where_value);
        $result = $this->conn->query("delete from $table where $where_conditional = $where_value");
        return $result;
    }

    public function select(string $table, array $feilds, string $where_conditional = null, array $where_value = null)
    {
        $feilds = implode(',',$feilds);
        if ($where_value === null and $where_conditional === null){
        $result = $this->conn->query("select $feilds from $table");
        }
        if ($where_conditional !== null and $where_value !== null){
            $where_value = array_map(fn($item)=>"'$item'",$where_value);
            $where_value = implode(',',$where_value);
            $result = $this->conn->query("select $feilds from $table where $where_conditional = $where_value");
        }
        if (isset($result)){
        return $result->fetchAll(PDO::FETCH_OBJ);
        }
    }

}

برای ارسال پاسخ لازم است وارد شده یا ثبت‌نام کنید

ورود یا ثبت‌نام