Implementing a CRUD class

Asked

Viewed 587 times

3

I have a class CRUD which has the following methods:

  • Get connection()
  • Insert($object)
  • Update($object)
  • Delete($object)
  • Select($object)

Taking into consideration the SRP (Principle of Sole Responsibility) which says:

A class should only have one reason to change.

My class CRUD from my point of view has more than one reason to change, because if I need to change the function Insert, I’ll have to change in class CRUD, the same occurs for other functions.

And then some doubts arose:

1 - According to the SRP my class has more than one reason to change, am I right? or this is not valid for type classes CRUD?

2 - Following the SRP what is the best way to create a class CRUD?

3 - Would it be ideal to have a class for each operation? or would it be better to use interfaces?

4 - In the case of interfaces, how the implementation would be made?

1 answer

2


to create this CRUD structure:

  • uses interfaces to define the methods that your classes will have implement.
  • create an abstract class to implement the methods;
  • create your CRUD class and extend this abstract class to get it now these implementations.
  • In your case, you can override the Insert methods in your CRUD class;

example of the structure:

interface ICRUD{
 public function Insert($objeto);
 public function Update($objeto);
 ...
}

abstract class BaseCRUD implements ICRUD{
  public function Update($objeto){
    //implementacao
  }

  public function Insert($objeto){
    //implementacao
  }
}

class Categoria extends BaseCRUD {
  public function Insert($objeto){  //sobrescreve 
    //implementacao personalizada para essa classe
  }
}
class Produto extends BaseCRUD {

}

example of use:

$produto = new Produto();
$produto->Insert($objeto);// implementacao feita no BaseCRUD

$categoria = new Categoria();
$categoria->Insert($objeto); //implementacao sobrescrita na class Categoria

Browser other questions tagged

You are not signed in. Login or sign up in order to post.