How much should a PHP class do? -


i'm oop nooby , i'm struggling grasp concept of how single class should do. i've seen lot of people class should 1 thing see lot of examples of classes doing more 1 thing. example, user login class.

say had class like

    class login {      public function __construct()     {         //connect database     }      public function checkcredentials()     {         //verify submitted username , password     }      public function login()     {         $this->checkcredentials();         //code log user in     } } 

would want handle user data (add functions pull user information such name, address, etc.) class, extend class, or entirely new class? if i'm going in wrong direction, guys please point me in right direction?

thanks in advance!

there plenty of articles , talks around topic.

generally speaking, recommended class should have one single responsibility. rule of thumb if takes more 1 sentence describe class, doing much.

an application should have lot of simple classes (that represent concept and/or logic) , classes act glue.

why recommended ?

it impacts how easy maintain , test code.

in example, have separated class each responsibility. again, example, can things in many different ways :

  • a user class represents structure of user (a representation of user entity or concept)
  • a userrepository class in charge of crud operations (this class have different implementations, example : 1 mysql, 1 mongodb, etc. therefore, having interface recommended).
  • a repositoryfactory in charge of instantiating adequate repository
  • a usersession class (could act glue between user , session classes)
  • a userservice class (could glue between application , userrepository, can used create user, update user, etc.)
  • session classes (could have multiple implementations, e.g. filesystem, apc, memcache, etc. therefore, create common interface).

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -