Answer the question
In order to leave comments, you need to log in
Array vs Switch case, code style best practice?
Good day.
I got something like this code in the project
public funciton getModelByTypeAndId($type, $id) {
switch ($name) {
case 'type0':
$offer = $this->em->getRepository(Type0::class)->find($id);
break;
case 'type1':
$offer = $this->em->getRepository(Type1::class)->find($id);
break;
case 'type2':
$offer = $this->em->getRepository(Type2::class)->find($id);
break;
case 'newType':
$offer = $this->em->getRepository(NewType::class)->find($id);
break;
case 'newType2':
$offer = $this->em->getRepository(NewType2::class)->find($id);
break;
case 'model':
$offer = $this->em->getRepository(Model::class)->find($id);
break;
default:
$offer = null;
}
return $offer;
}
public funciton getModelByTypeAndId($type, $id) {
$classes = [
'type0' => Type0::class,
'type1' => Type1::class,
'type2' => Type2::class,
'newType' => NewType::class,
'newType2' => NewType2::class,
'NewType3' => NewType3::class,
];
if (empty($classes[$name])) {
return null;
}
return $this->em->getRepository($classes[$name])->find($id);
}
public funciton getModelByTypeAndId($type, $id) {
switch ($type) {
case 'auto' : $entity = Type0::class; break;
case 'type1' : $entity = Type1::class; break;
case 'type2' : $entity = Type2::class; break;
case 'newType' : $entity = NewType::class; break;
case 'newType2': $entity = NewType2::class; break;
case 'newType3': $entity = NewType3::class; break;
default : return null;
}
return $this->em->getRepository($entity)->find($id);
}
public funciton getModelByTypeAndId($type, $id) : IEntityWithAlias {
switch ($type) {
case Type0::getAlias() : $entity = Type0::class; break;
case Type1::getAlias() : $entity = Type1::class; break;
//и т.д.
default : throw new InvalidArgumentException('Unknown category type');
}
return $this->em->getRepository($entity)->find($id);
$classes = [
Type1::class,
Type2::class,
Type3::class,
NewType1::class,
///и т.д.
];
foreach ($classes as $class) {
if ($class::getAlias() === $name) {
return $this->em->getRepository($class)->find($id);
}
}
throw new InvalidArgumentException('Unknown category type');
Answer the question
In order to leave comments, you need to log in
https://en.wikipedia.org/wiki/Open_Principle/z...
The second option is close to what you want, but it has an explicit enumeration, which you need to get rid of.
Make a setter (type, class) in this method, and in your service configuration, inject classes with the corresponding types there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question