Answer the question
In order to leave comments, you need to log in
What is wrong with creating classes?
There is a website that publishes news. News can be created by both the administrator and registered visitors of the site. News is stored in the database in a single news table .
id: integer
type: integer
model_id: integer DEFAULT NULL
image: varchar(255)
content: blob
Answer the question
In order to leave comments, you need to log in
If we discuss "architecturally correct" ways to resolve such a situation in OOP and in Yii2 in particular - I can say that your case falls under the case of single table inheritance - here is an excellent example from the manual how to prepare it.
As a result, when iterating over the News::find()->all() array, you will not have News instances there, but NewsAdmin and NewsUser. Is the above pattern overengineering in your situation? It's up to you to decide :) perhaps it's easier to really not worry and hardcode everything in the base class.
You can put the type->path connection into the config, then you won't need the NewsUser and NewsAdmin classes. And the getPathToImages() method will return the path depending on the type.
You can put the type->className connection into the config, then having received the class name from the config in the code, you can create an object $news = new $className($param);
The first option is preferable if there is no other reason to use inheritance.
2 tables for this task - it's really strange
Create a common one in getPathToImages(); pass parameters:
getPathToImages($image, $user)
and pass via $user everything, admin or user
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question