I'm new to PHP and I'm working on Symfony 4 project
I've made a Java project using an Enum Class called role
public class Role {
public enum RoleEnum {
Admin, SuperAdmin, Etudiant, Entreprise } private Short id;
private RoleEnum name;
public Role(Short id, RoleEnum name) {
this.id = id;
this.name = name ;
}
and in my user I made it like this
public abstract class User {
private Long id;
private String nom;
private String email;
private String mdp;
private String tel;
private String photo;
private Role role;
private Boolean etatCompte;
and I've made a relation between the two tables in MySQL
and I created this method in Java too
public Role getRoleByName(RoleEnum input) {
Statement stm;
try {
stm = cnx.createStatement();
String query = "SELECT id from role Where name='" +input+"'";
ResultSet rst = stm.executeQuery(query);
while (rst.next()) {
Short id = rst.getShort("id");
return new Role(id, input);
}
} catch (SQLException ex) {
Logger.getLogger(ServiceEtudiant.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
and when I'm adding values to the table for example to add "admin" to the role I do it like this
Role role = s.getRoleByName(Role.RoleEnum.Admin);
can anyone help me or guide how to do it the sameway in my symfony project?
In PHP you can create associative arrays like:
[
"FIRST" => 1,
"SECOND" => 2,
"THIRD" => 3,
"FOURTH" => 4,
]
An improvement on this is to create the keys as variables as well:
$FIRST = "FIRST";
$SECOND = "SECOND";
$THIRD = "THIRD";
$FOURTH = "FOURTH";
$myenum = [
$FIRST = 1,
$SECOND = 2,
$THIRD = 3,
$FOURTH = 4,
];
You can create an enum generator
class MyEnum {
public function __construct($keysValues) {
foreach ($keysValues as $key => value) $this->{$key} => $value;
$this->values = $values;
}
}
Instantiation:
$numbers = new MyEnum(
[
"FIRST" => 1,
"SECOND" => 2,
"THIRD" => 3,
"FOURTH" => 4,
]);