Answer the question
In order to leave comments, you need to log in
How to create links between objects?
Hello. Where to read or explain who knows about this case.
We have
class Operation
{
public $id;
public $date;
public $user_id;
// Далее сеттеры, геттеры
}
class Operation {
// ...
public $user
// Добавить User $user = new User::find($this->$user_id)
public setUser(User $user) {
$this->user = $user;
}
}
Answer the question
In order to leave comments, you need to log in
1. Logically, if an operation cannot exist without a user, then when creating an object, it must be mandatory new Operation(new User("username"));
2. public setUser() - incorrectly implemented, so it is necessary: setUser(User $user)
3. Working with nested objects is correct, but you need to understand that in order to transfer such an object to the storage layer, you will need to write a datamapper that will transform the object into a database storage format . As a rule, ORM immediately provides a toolkit for this.
I may not understand, but:
class Operation {
// ...
}
class UserOperation extends Operation {
// ...
}
It will probably be interesting for you to read about AR: codengineering.ru/post/3
If I understand correctly, you are interested in the question of how to convert the related data from a relational representation into an object one. In this case, I recommend reading about the Foreign Key Mapping pattern. You can read Fowler, (well, or just google)
Option 1.
As mentioned above, a user object is strictly necessary to know its ID.
When saving, we write the ID of the user object in the operations table or, in a separate table of links, if a one-to-many relationship is expected.
When saving the Operation model, the DM has a code in the save method that is responsible for linking the operation and the user.
Roughly speaking, the operation::save() method has an implementation that saves the relationship.
The Operation model has lazy load methods that allow you to grab the user object:
$operation->getUsers();
Option 2.
We implement a system in which we store any connections between objects in ONE table:
id of the object that is attached
id of the object to which it is attached
model (for example, class name) that is bound
model (for example, class name) to which it is bound
- here you can link any objects in the system
due to the model object ID and class name, unique links are achieved:
234 | 567 | \my\namespace\user | \my\namespace\operation
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question