Sorry if this has been asked before but Googling didn’t give it to me.
How do you protect methods (or properties) from only unrelated classes, but have it available for specific, related classes?
class supplier {
protected person $contactPerson;
}
class unrelated {
function unrelatedStuff(supplier $supplier) {
$noneOfMyBusiness = $supplier->contactPerson; // should generate error
}
}
class order {
function __construct(readonly public supplier $supplier) {}
function informAboutDelivery() {
$contact = $this->supplier->contactPerson;
// should work (but doesn't) since to process an order you need the suppliers details
$contact->mail('It has been delivered');
}
}
I wrote a trait that can allow access to certain predefined classes to certain methods, whilst disallowing all other access, with a __method magic method and attributes. I can also think of using Reflection. But I feel that’s all overcomplicated and that I am missing something quite obvious here. Many classes are very closely related, others are unrelated. What is the normal way to deal with this? How do you shield information but not from all classes?
2
Answers
Another solution (still not very elegant, but more elegant than magic methods) that would work in quite a few cases, also restricts access to orders only for this particular supplier (which is more strict but that's good in this case), could be:
This returns the supplier only if called from the class orders as such:
The problem that I have with it, is that you will have to copy the code every time you want to use it, it's not a structural solution.
So I moved on to a more structural solution. This is the best I found (could also be done with implements instead of a trait):
Which is a bit complicated, but efficient. This hack wouldn't work:
What about using a magic method with a backtrace?