Skip to content

Instantly share code, notes, and snippets.

@fesor
Last active March 12, 2024 00:02
Show Gist options
  • Select an option

  • Save fesor/d84451fc6cf00ea62ca5 to your computer and use it in GitHub Desktop.

Select an option

Save fesor/d84451fc6cf00ea62ca5 to your computer and use it in GitHub Desktop.
Доступ к данным или как мы учились не замечать базу данных

Собственно тут описана основная разница между подходами ActiveRecord и DataMapper. Гидраторы можно впихнуть туда и туда, можно мэпить на любые структуры теоритически, но основное различие в том кто отвечает за сохранение данных.

<?php
class User extends ActiveRecord {
public $id;
public $email;
public $password;
public $firstName;
public $lastName;
}
/* maps all this on table:
Table users
------------------------
| id | int |
| email | string |
| password | string |
| first_name | string |
| last_name | string |
------------------------ */
abstract class ActiveRecord {
public function save() {
if ($this->isNewRecord()) {
$this->insert();
} else {
$this->update();
}
}
public function update() {
$this->db->update($this->tableName, $this->attrs, ['id' => $this->id]);
}
public function insert() {
$this->db->insert($this->tableName, $this->attrs);
}
public function delete() {
$this->db->insert($this->tableName, $this->attrs);
}
// ...
}
<?php
class User {
private $id;
private $email;
private $password;
private $profile;
public function __construct(string $email, string $password, UserProfile $profile) {
$this->email = $email;
$this->password = $password;
$this->profile = $profile;
}
}
class UserProfile {
private $firstName;
private $lastname;
public function __construct(string $firstName, string $lastName) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
/** Maps data to this table structure:
*
* ------------------------------
* id | int |
* email | string |
* password | string |
* profile_first_name | string |
* profile_last_name | string |
*/
class DataMapper {
private $db, $hidrator;
public function save(User $user) {
$attributes = $this->hidrator->dehydrate($user);
if ($this-isNewRecord($user)) {
$this->db->setIdentity($user); // selects next sequence value as ID (only postgresq, oracle, mssql)
$this-db->insert($this->getTableName($user), $attributes);
} else {
$this->db->update($this->getTableName($user), $attributes, $this->getFindByIdentityCriteria($user));
}
}
public function remove(User $user) {
$this->db-delete($this->getTableName($user), $this->getIdentity($user));
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment