Gihanmu
Gihanmu

Reputation: 407

How to reuse mysql CRUD in PHP?

I have an idea, but I don't know how to implement it. Let's say there are various tables in our db and each table may have different fields. I need to create a parent class which has some common database functions for CRUD (create, read, update and delete). (It might take the table name as an argument). We can re-use all these CRUD methods in our sub-classes. We don't have to specify field names.

class AllCRUD{

  protected function select (){
   // select * from ..... comes here

  }

  protected function create (){
   // select * from ..... comes here

  }

  // update and delete comes then


} 

class Users extends ALLCRUD{
    protected $table_name="users";

    //Mechanism to iterate through field names

}

//create the object
$user=new Users();
$user->select() 
//This will select all users from users table
//Likewise we must be able to perform insert, update and delete on any subclass

I believe you guys may have understood what I am trying to say I need someone's help to implement this concept. If there is a blog or something that I can read, please post the link. (I searched, but did not find something which fits for my purpose)

Thanks

Upvotes: 3

Views: 958

Answers (2)

lihsus
lihsus

Reputation: 297

You can refer to a very early version of a lightweight simple ORM framework with just few files and easy to use and understand.

PHP Tiny Framework: https://github.com/sushilman/ptf

It does not provide enough security by itself (like: against SQL injection ) which you will have to take care of by yourself.

If your project is large enough and if you want other features of a framework, then I would recommend you to use one of several available PHP frameworks : Zend, CodeIgniter, Symphony and so on.

Upvotes: 2

Barif
Barif

Reputation: 1552

Recently I was doing exactly the same problem

And extended child EventModel

In my example, Event Model inheritance AbstractCRUDModel and implement this logic. For example:

//create model object
$eventModel = new EventModel();
// fetching from database
$event = $eventModel->read(1);

Upvotes: 2

Related Questions