Implement a CRUD class

3

I have a CRUD class that has the following methods:

  • GetConnection ()
  • Insert ($ object)
  • Update ($ object)
  • Delete ($ object)
  • Select (object)

Taking into account the SRP (Principle of Single Responsibility) that 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 Insert function, I will have to change in class CRUD , same for other functions.

And then some doubts came up:

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

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

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 would the implementation be done?

    
asked by anonymous 23.08.2015 / 18:08

1 answer

2

to create this structure CRUD:

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

structure example:

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 {

}

usage example:

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

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