how do you design your objects lets say you have an object user and an object access_role. The user is stored in users table in an sql database, the access_role knows the user_id and is stored in an sql database.
class user() {
protected $_name;
protected $_id;
protected $_age;
protected $_password;
public function getName();
public function getId();
public function getAge();
public function getPassword();
public function setName();
public function setId();
public function setAge();
public function setPassword();
//sql query
public function read(){};
}
class accessRole {
protected $_accessRole;
protected $_userId;
public function setAccessRole();
public function setUserId();
public function getAccessRole();
public function getUserId();
}
If i want the access role for the user in do an query in sql. But how do you connect both objects, so that something like:
$u = new User();
$u->getAccessRole();
will work?
I’d separate the base user and roles class by having an intermediator between them.
This way
class userandclass accessRoledo not have to know each other or any of their respective properties.class usercan happily live without access roles andclass accessRoleisn’t bound to $_userId. E.g. what would the userid be for an accessRole soley based on the time of day? (Ok, silly example. Hope you get the point). You may even translate roles for various subsystems without the need to carry all the specific (sub-)roles throughout the system.edit: (hopefully) short example….
I’m using a simple User class (no further interfaces or other kinds of abstraction) and there’s no Roles “class”, just a simple string array (for brevity’s sake). But keep in mind that you can do a lot more decoupling …if you like.
Now you can have code that relies on the user class and the UserRolesProvider interface but let’s you change the implementation of the provider without touching all the other code. Or it even only relies on the collection of Roles which let’s you build/create/assemble the Roles as you like. Ok, let’s have two (dummy) implementations of the provider interface.
and some User objects
and something that uses both
prints
Not too impressive. But the point is you don’t have to touch the User class or the code in function foo().
And the decoupling can go on and on …if you like.
E.g. a registry that can answer to “I have some [type] here. Can you give me something that builds roles from it?”
Or maybe even “Can you build me a stub so that I can call fn($roles) as fn([type])?”