El ejemplo Role Demo usa Doctrine ORM para gestionar la base de datos. Nosotros ya hemos aprendido como usar Doctrine en el capítulo Administrar la base de datos con Doctrine ORM.
Para almacenar la información sobre los roles y permisos en la base de datos,
crearemos las entidades Role
y Permission
. La entidad Role
está asociada
con la tabla de base de datos role
, mientras que la entidad Permission
está asociada a la tabla permission
. Estas son típicas clases de entidad
de Doctrine.
Creamos un archivo Role.php dentro de la carpeta Entity que está dentro de la carpeta fuente del módulo User. Colocamos el siguiente código dentro del archivo:
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* This class represents a role.
* @ORM\Entity()
* @ORM\Table(name="role")
*/
class Role
{
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\Column(name="name")
*/
protected $name;
/**
* @ORM\Column(name="description")
*/
protected $description;
/**
* @ORM\Column(name="date_created")
*/
protected $dateCreated;
/**
* @ORM\ManyToMany(targetEntity="User\Entity\Role")
* @ORM\JoinTable(name="role_hierarchy",
* joinColumns={@ORM\JoinColumn(name="child_role_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="parent_role_id", referencedColumnName="id")}
* )
*/
private $parentRoles;
/**
* @ORM\ManyToMany(targetEntity="User\Entity\Role")
* @ORM\JoinTable(name="role_hierarchy",
* joinColumns={@ORM\JoinColumn(name="parent_role_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="child_role_id", referencedColumnName="id")}
* )
*/
protected $childRoles;
/**
* @ORM\ManyToMany(targetEntity="User\Entity\Permission")
* @ORM\JoinTable(name="role_permission",
* joinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="permission_id", referencedColumnName="id")}
* )
*/
private $permissions;
/**
* Constructor.
*/
public function __construct()
{
$this->parentRoles = new ArrayCollection();
$this->childRoles = new ArrayCollection();
$this->permissions = new ArrayCollection();
}
/**
* Returns role ID.
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Sets role ID.
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDateCreated()
{
return $this->dateCreated;
}
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
}
public function getParentRoles()
{
return $this->parentRoles;
}
public function getChildRoles()
{
return $this->childRoles;
}
public function getPermissions()
{
return $this->permissions;
}
public function addParent(Role $role)
{
if ($this->getId() == $role->getId()) {
return false;
}
if (!$this->hasParent($role)) {
$this->parentRoles[] = $role;
return true;
}
return false;
}
public function clearParentRoles()
{
$this->parentRoles = new ArrayCollection();
}
public function hasParent(Role $role)
{
if ($this->getParentRoles()->contains($role)) {
return true;
}
return false;
}
}
Como podemos ver en el código de arriba, la entidad Role es una típica entidad de Doctrine que tiene propiedades expresadas mediante anotaciones y métodos getter y setter para recuperar y asignar estas propiedades.
Luego, creamos el archivo Permission.php dentro de la carpeta Entity que está dentro de la carpeta fuente del módulo User. Colocamos el siguiente código dentro del archivo:
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* This class represents a permission.
* @ORM\Entity()
* @ORM\Table(name="permission")
*/
class Permission
{
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\Column(name="name")
*/
protected $name;
/**
* @ORM\Column(name="description")
*/
protected $description;
/**
* @ORM\Column(name="date_created")
*/
protected $dateCreated;
/**
* @ORM\ManyToMany(targetEntity="User\Entity\Role")
* @ORM\JoinTable(name="role_permission",
* joinColumns={@ORM\JoinColumn(name="permission_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
private $roles;
/**
* Constructor.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDateCreated()
{
return $this->dateCreated;
}
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
}
public function getRoles()
{
return $this->roles;
}
}
Finalmente, extenderemos un poco la entidad User
que ya fue creada para el
sitio web User Demo, agregamos las propiedades y los métodos relacionado
con los roles:
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* This class represents a registered user.
* @ORM\Entity()
* @ORM\Table(name="user")
*/
class User
{
// User status constants.
const STATUS_ACTIVE = 1; // Active user.
const STATUS_RETIRED = 2; // Retired user.
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\Column(name="email")
*/
protected $email;
/**
* @ORM\Column(name="full_name")
*/
protected $fullName;
/**
* @ORM\Column(name="password")
*/
protected $password;
/**
* @ORM\Column(name="status")
*/
protected $status;
/**
* @ORM\Column(name="date_created")
*/
protected $dateCreated;
/**
* @ORM\Column(name="pwd_reset_token")
*/
protected $passwordResetToken;
/**
* @ORM\Column(name="pwd_reset_token_creation_date")
*/
protected $passwordResetTokenCreationDate;
/**
* @ORM\ManyToMany(targetEntity="User\Entity\Role")
* @ORM\JoinTable(name="user_role",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
private $roles;
/**
* Constructor.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
}
/**
* Returns user ID.
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Sets user ID.
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Returns email.
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Sets email.
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Returns full name.
* @return string
*/
public function getFullName()
{
return $this->fullName;
}
/**
* Sets full name.
* @param string $fullName
*/
public function setFullName($fullName)
{
$this->fullName = $fullName;
}
/**
* Returns status.
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Returns possible statuses as array.
* @return array
*/
public static function getStatusList()
{
return [
self::STATUS_ACTIVE => 'Active',
self::STATUS_RETIRED => 'Retired'
];
}
/**
* Returns user status as string.
* @return string
*/
public function getStatusAsString()
{
$list = self::getStatusList();
if (isset($list[$this->status]))
return $list[$this->status];
return 'Unknown';
}
/**
* Sets status.
* @param int $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* Returns password.
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Sets password.
* @param string $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Returns the date of user creation.
* @return string
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Sets the date when this user was created.
* @param string $dateCreated
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
}
/**
* Returns password reset token.
* @return string
*/
public function getResetPasswordToken()
{
return $this->passwordResetToken;
}
/**
* Sets password reset token.
* @param string $token
*/
public function setPasswordResetToken($token)
{
$this->passwordResetToken = $token;
}
/**
* Returns password reset token's creation date.
* @return string
*/
public function getPasswordResetTokenCreationDate()
{
return $this->passwordResetTokenCreationDate;
}
/**
* Sets password reset token's creation date.
* @param string $date
*/
public function setPasswordResetTokenCreationDate($date)
{
$this->passwordResetTokenCreationDate = $date;
}
/**
* Returns the array of roles assigned to this user.
* @return array
*/
public function getRoles()
{
return $this->roles;
}
/**
* Returns the string of assigned role names.
*/
public function getRolesAsString()
{
$roleList = '';
$count = count($this->roles);
$i = 0;
foreach ($this->roles as $role) {
$roleList .= $role->getName();
if ($i<$count-1)
$roleList .= ', ';
$i++;
}
return $roleList;
}
/**
* Assigns a role to user.
*/
public function addRole($role)
{
$this->roles->add($role);
}
}