Php DAL - separate object and database?

I studied and read a lot about working with individual layers in PHP to create supported and readable code. However, I see a lot of code in which the object and access to the database are placed in one class. For instance:

class User{
     public $id;
     public $username;
     public $database;

     function add(){
           $database->query ....
     }
}

I find this rather strange, because here you are mixing the User class with database elements, which makes it difficult to maintain.

I like to work as follows:

  • separate database class
  • user class
  • class userData li>

This works as follows:

$database = new Database();
$database->openConnection();
$dataUser = new DataUser($db);
$user = new User(1,"myname");
$dataUser->saveUser($user);

So, I am wondering if I am working correctly or is this the best way to create code? I find it very easy to maintain, because you have a separate object and a separate database class for processing database actions.

+5
source
3

,

, , Active Record Data Mapper/Entity/Repository. , . , , Doctrine, - :

$product = new Product();
$product->setName($newProductName);
$entityManager->persist($product);

$product - POPO ( PHP), , , , , , .

+1

, UserData User . UserData, , ProductData, , add($data), find($id) ..

User MVC, / . , , , User, . ORM. , , .

+1

:

, ( ), " ". , (, n , , ).

class User{
private $name;
private $password;
// getter and setters
}

, -, , .

class UserService{
    function __construct(IUserProvider $userProvider){
        $this->userProvider = $userProvider
    }
    function getUsers(){
       // return an array of user objects
       return $this->userProvider->getUsers();

    }
}

, , , , , json , webservice:

 class UserProvider implements IUserProvider{
      function __construct(Connection $connection){
         $this->connection = $connection;
      }
      function getUsers(){
         return $this->toUsers($this->connection->fetchAssoc("Select * from users"));
      }
      function toUsers(array $datas){
          // convert user records to an array of User
          (...)
          return $users;
      }
 }

interface IUserProvider{
     /**@return array an array of User */
     function getUsers();
}

, , . , , 2 . UserProvider, CommentProvider.

3 :

  • ( , ...)
  • ( -, , , ACL , ...)
  • , ,

- , .

, .

, , : https://github.com/Mparaiso/silex-bookmarkly

.

+1

All Articles