php DAL - separate entity and database? -


i've been researching , reading lot working separate layers in php create maintainable , readable code. however, see lot of code entity , database access placed in 1 class. example:

class user{      public $id;      public $username;      public $database;       function add(){            $database->query ....      } } 

i find rather strange because here mixing user class database elements makes more difficult maintain.

i working this:

  • a separate database class
  • a user class
  • a userdata class

this works this:

$database = new database(); $database->openconnection(); $datauser = new datauser($db); $user = new user(1,"myname"); $datauser->saveuser($user); 

so i'm wondering, working right way or first way better way create code? find may way easy maintain because have separate entity , separate database class handle database actions.

easy maintain because have separate entity , separate database class

it appears you're saying wish move away active record approach data mapper/entity/repository approach. that's direction move in because employs better separation of concerns. can build might want take @ solutions doctrine allows along lines of:

$product = new product(); $product->setname($newproductname); $entitymanager->persist($product); 

the $product entity popo (plain old php object) contains record data , unaware of how it's persisted and, when persistence needed, passed entity manager take care of storing.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -