PHP отделяет MySql запросы от классов

Кажется, все мои классы, которые я создаю, заполнены методами, которые содержат запросы MySql. Я решил сделать снимок развязки. Ниже у меня есть свой базовый класс Customerи мой класс хранилища CustomerRepository это передается конструктору, если это необходимо. Методы являются основными, save метод в клиенте
вызывает create метод в CustomerRepository например. Класс клиента теперь немного читабельнее, но какой ценой? Я кодировал целый другой класс только для того, чтобы выполнить запрос MySql, который я мог бы поместить в create метод в Customer класс для начала. Я изо всех сил пытаюсь найти реальный пример развязки, который будет работать в этом сценарии, поскольку это относится к рабочему проекту. Примеры, которые я нашел, такие как здесь, Правильный ли шаблон репозитория в PHP? (хотя и фантастически), кажется слишком сложным. Мой вопрос (ы): правильно ли я отделить? и требуется ли разделение, даже если в реальном мире требуется быстрый и несколько грязный код для максимально быстрого достижения цели бизнеса?

<?php

/*
CRUD
create, read, update, delete
*/

class Customer {

public $CustomerRepository;

public $id;
public $first_name;
public $last_name
public $email;
public $phone;

public function __construct( CustomerRepository $CustomerRepository = null ) {
if( !is_null( $CustomerRepository ) {
$this->CustomerRepository = $CustomerRepository;
}
}

public function save() {

return $this->CustomerRepository->create(
$this->first_name,
$this->last_name,
$this->email,
$this->phone
);

}

public function find() {

return $this->CustomerRepository->read( $this->id );

}

public function edit() {

return $this->CustomerRepository->update(
$this->first_name,
$this->last_name,
$this->email,
$this->phone,
$this->id
);

}

public function remove() {

return $this->CustomerRepostitory->delete( $this->id );

}

public function populate( $id ) {

$customer = $this->find( $id );
$this->id         = $customer['id'];
$this->first_name = $customer['first_name'];
$this->last_name  = $customer['last_name'];
$this->email      = $customer['email'];
$this->phone      = $customer['phone'];

}

}

class CustomerRepository {

private $Database;

public function __construct() {
if( is_null( $this->Database ) {
$this->Database = new Database();
}
}

public function create( $first_name, $last_name, $email, $phone ) {

$this->Database->query( 'INSERT INTO customers( first_name, last_name, email, phone )
VALUES( :first_name, :last_name, :email, :phone )' );
$this->Database->bind( ':first_name', $first_name );
$this->Database->bind( ':last_name', $last_name );
$this->Database->bind( ':email', $email );
$this->Database->bind( ':phone', $phone );

return $this->Database->getLastID();
}

public function read( $id ) {

$this->Database->query( 'SELECT * FROM customers WHERE id = :id LIMIT 1' );
$this->Database->bind( ':id', $id ):

return $this->Database->single();

}

public function update( $first_name, $last_name, $email, $phone, $id ) {

$this->Database->query( 'UPDATE customer SET
first_name = :first_name,
last_name  = :last_name,
email      = :email,
phone      = :phone WHERE id = :id' );
$this->Database->bind( ':first_name', $first_name );
$this->Database->bind( ':last_name', $last_name );
$this->Database->bind( ':email', $email );
$this->Database->bind( ':phone', $phone );
$this->Database->bind( ':id', $id );

return $this->Database->execute();
}

public function delete( $id ) {

$this->Database->query( 'DELETE FROM customers WHERE id = :id LIMIT 1' );
$this->Database->bind( ':id', $id ):

return $this->Database->execute();

}

}

3

Решение

Как все уже предложили, вам нужно внедрить ORM. Посмотрите этот вопрос, чтобы выбрать: Хорошая PHP ORM библиотека?

Если вы по-прежнему не хотите использовать ORM, вам нужно будет реализовать то же самое само по себе, это займет больше времени, чем использование готового к использованию ORM. Вы могли бы реализовать Единица работы (http://martinfowler.com/eaaCatalog/unitOfWork.html
) а также вместилище (http://martinfowler.com/eaaCatalog/repository.html) шаблоны для создания собственной ORM.

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector