Answer the question
In order to leave comments, you need to log in
How to combine the work of two methods?
There is a class Customer
The method create()
creates a record about the client
The method createContact()
creates a record in the contacts table. There can be several contacts for one client.
Since a record is added from immediately for both the first and second tables (one contact definitely needs to be saved, and in one action), it is not clear how to implement this in the controller.
The only thing that came to my mind was to do this:
if(isset($_POST['create'])){
try{
$last_id = $customer->create($_POST); //метод возвращает новый номер записи
if(!empty($last_id)){
$customer->createContact($last_id, $_POST); //передаем его в метод добавления контакта
}
}catch(AppException $e){
}
}
createContact
inside create
, inside the class
Answer the question
In order to leave comments, you need to log in
1. In principle, there should never be anything like this in the controller. Not two methods, not one. In principle, there can be no work with the database in the controller. The controller only needs to accept the data from the form and call the model's method. Only not a poor class for mapping a table from a database into a PHP class, which is called the beginner model, but a normal model that implements the entire business logic of the application.
2. In a good way, this is the code for the repository , since it works with the database. But the specific implementation depends on how the customer class is implemented
. Ideally, the call chain should be like this
The controller calls the instance of the helper (or service) CustomerHelper.
The CustomerRepository instance is passed to this helper via the constructor and assigned to a property of the class.
In the Create method of the CustomerHelper class, the Create method of the CustomerRepository class is called.
And in this method, the desired transaction is already happening.
If you add to 2 tables at once, then wrap it in a transaction and then call one method reliably
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question