I'm trying to use the strategy pattern to solve a design issue. It's a college system. There is an User, and the user can be either a Student, a Professor or an Administrator. So, I have an User
entity like this
<?php
namespace Domain\Model\User;
class User
{
private $user_type;
public function __construct(UserType $user_type)
{
$this->user_type = $user_type;
}
public function hasAccess()
{
$this->type()->hasAccess();
}
// others methods
}
The UserType
is an Interface, that each user type implements it. Like the StudentType
:
<?php
namespace Domain\Model\User;
class StudentType implements UserType
{
public function hasAccess()
{
// checks if has access
}
}
Notice that I don't want to create an ACL with Strategy Pattern
, I'm already using one. The point here is that each type of user has a proper way to access an environment, so I have to do some checks.
So the question is the method type()
of the User
entity. I know that I don't have to think about database when modeling my entities, but all these types, users, students are stored in a relational database, and I can't avoid this. So, I'm using Doctrine
for persistence.
When I retrieve an User
from the database, Doctrine don't uses the constructor of my User
, so the $user_type
attribute will be only a number. Then, to guarantee that $user_type
property will always be a class that implements the UserType
interface, I had to use the type()
method to do something like this
// method inside User class
public function type()
{
if (!$this->user_type instanceof UserType) {
switch ($this->user_type) {
case 1:
$this->user_type = new StudentType;
break;
// some others ugly conditions for each type
}
}
return $this->user_type;
}
Is there a way to avoid using these conditionals? Or am I thinking in the wrong way about Strategy Pattern?