1

I send variables to my route via an ajax post. Based on the value of my type value I create a new Object, like this:

if($request->get('type') === 'HardwareType'){
    $e = new HardwareType();
}else if($request->get('type') === 'SetupType'){
    $e => new SetupType();
}else{
    new NotFoundHttpException();
}

This gets out of hand quickly even with a switch I think its still "ugly". Is there any way I could do sth. like this:

$e = new $request->get('type')();

Any hint appreciated

EDIT I use the class(es) with this use AppBundle\Entity\HardwareType; etc.

1
  • Why not use a container, each class(or service, or whatever) can have an alias. Instead of doing new HardwareType you can use $container->get('class_service_whatever_id);` Commented Sep 19, 2017 at 13:49

2 Answers 2

3

you can do this:

$e = $request->get('type');
$class = new $e();

If you need you can add the path or the class like this:

$e = 'AppBundle\Entity\' . $request->get('type');

Obviously you need to add use at the begin of the file and you can check before the new if the class exist or not

Like this:

if (!class_exists($e)) {
   //exception
}
Sign up to request clarification or add additional context in comments.

10 Comments

That has potential to fail without any checks
Hackers would love this in combination with a vulnerable Composer library
@Pete IKR? More strictness required!
Thanks for the concerns, it's an internal project only with no intention to ever go public. However, is there a safe approach? It worked btw. like a charm so I will accept this in any case! Thank you
Take a look into the factory-pattern, maybe this is what you need.
|
2

Just use an associative array! Define the acceptable classes, so that other types of class you don't want to allow can't be instantiated!

Then just check the key is in the array, and if so create a new Whatever()!

$types = [
    'HardwareType' => HardwareType::class,
    'etc' => SomeOther::class
];

$getVar = $request->get('type');

// So all you need do is 
if (array_key_exists($getVar, $types)) {
    $e = new $types[$getVar]();
} else {
    throw new NotFoundHttpException();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.