Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

php - OOP : clone object to descendant class

Here is a OOP design/code question. I wil try to simplify my problem to clarify. I have a PecCollection class that represent a collection of Pec objects (a Pec is a "Prise en charge", it's not very important to describe what is it. You can see it as any object a person should possess).

Each Pec "belongs to" a Person, when and Person is created, it has his own PecCollection that list all of his Pecs. PecCollection is just a class storing an array of Pecs. The Pecs objects are created from data taken in the database.

Person(0,1) --has-> PecCollection(1,n) --contains--> Pec

Now, I possibly (but maybe NOT) want to make a list of controls on each Pec and store datas about theses controls about each Pec (let's say "An amount of hours", hoursNb, for example).

What I could make is simply add a "nbHours" property on Pec Class, and store the nbHours given by the controle in that property. But this, I think (maybe I'm wrong), isn't a good way of doing : it changes the responsability of the Pec Class (represent a basic Pec) to several responsabilities (represent a basic Pec AND and controled pec). Moreover, not all the Pec will be controled.

I could make a ControledPec Class that inherits from Pec, with the nbHours property in addition. It seems to be a good solution. ANd I could store theses objects in a ControlledPecCollection for each Person.

Person(0,1) --has--> PecCollection(1,n) --contains--> Pec<--is a-- ControlledPec

But there, here is my problem. How can I create (AND : is it a good practice ?) the controledPecs objects from Pec Objects that already exists, without having to re-create controledPecs, by searching datas in the databse (as for Pec) ? Knowing that a ControledPec will always be a specialization of a Pec that already exists ?

I am in PHP.

Thank you i advance.

question from:https://stackoverflow.com/questions/65885044/oop-clone-object-to-descendant-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to Felipe, Decorator seems to be the good solution here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...