راکت
حل شده

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

1 پاسخ

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

ثبت پرسش جدید

پاسخ‌ها

1
امیر حسین
امیر حسین
@kalanamir815

تخصص: وردپرس کار

بهترین پاسخ

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

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);
        }
    }

}

شاید پاسخ شما همین‌جا باشد

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

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