What are the relative advantages / disadvantages of chaining classes together (or rather; using the results of one class to generate another), compared to nesting classes?
I’m trying to restructure my user / authentication system and am wondering whether;
- myAuthClass should act as a utility and if log-in is successful, simply create a new myUserClass object
- or whether the myAuthClass should create the myUserClass internally (ie $this->user = new myUserClass)
- or even if myUserClass should just call myAuthClass when necessary (ie when a user tries to log in) and update its internal structure (new emails, favourites, cart, etc) as necessary.
As you can tell I’m a bit of an OOP n00b. Concpetually I seem to be able to make a case for each of the methods, so I’m interested in hearing from other people regarding the +ves/-ves of the various approaches.
Cheers.
From an accademic perspective, all 3 options are incorrect in that they are programmed against concrete implementations and not against an abstract interface. As such they are directly coupled together, which limits reuse – you re-use them both or not at all.
You could generate IUserClass, or IAuthClass and implement this abstract interface into a concrete class and then I would go for a situation where the auth class implementation took an IUserClass when authenticating to populate, or the user class was given an implementation of IAuthClass to authenticate against.
In each scenario this allows the most flexability, in that the auth class can be reused and different versions of the UserClass can be generated, or the user class has the ability to use multiple different authentication mechanisms, as long as the inherit from IAuthClass.
The latter approach of giving the user class an authentication object (that implements IAuthClass) would be my preference, in that authentication mechanisms differ, even with a single application, whilst the user class would change less. But to be correct, neither should be based on a concrete implementation.
This can however be seen as over the top, so it’s a judgement call.