Search code examples
phpsymfonyswitch-statementgetter-setter

getter/setter Class from $variable w/out switch/if in Symfony?


I am using a table edit switch, which I want to integrate to Symfony. This is the script I am talking about: LINK

Now this script sends requests that I am able to receive in symfony.

Sender

<a href="#" id="Username" data-type="text" data-pk="1" data-url="/post/table1" data-title="Enter username">superuser</a>

Receiver (/post)

if($table == "table1"){
    $repo = "AppBundle:Table1";
}
...
/* Get correct repo/entry */
$repo = $em->getRepository($repo)->find($request->get('pk'));

That is somehow untested but should work I guess.

Now I want to update the according column, which is sent by id="Username"

What I'd like to achieve now is something like this: (I know this won't work) $repo->set.$request->get('id')('blabla')

I could use a switch, but that needs to be quite large then.

Any other approach to this?

PS: I know it is not very safe to send values like this, but it's only for personal use.


Solution

  • If you want call a setter from your request value, the following code will work :

    $setter = 'set'.$request->request->get('id'); // is now equal to 'setUsername'
    $repo->$setter('blabla'); // Assuming $repo is the entity retrieved by find();
    

    Also, there is a clean way to do that is symfony called PropertyAccess, you just need the name of the property you want set/get .

    Example :

    use Symfony\Component\PropertyAccess\PropertyAccessor;
    // ...
    $accessor = PropertyAccess::createPropertyAccessor();
    
    // If the property 'username' is writable, set it
    if ($accessor->isWritable($repo, 'username') {
        $accessor->setValue($repo, $request->request->get('id'), 'blabla');
    }
    

    See Symfony PropertyAccess