I have been playing around with some neat ways to do things with symfony2 and the validator component. In this post I will show you one way to use the validator component in your commands. We will start with this base template.
Please note, Symfony2 Commands can be either interactive or noninteractive. It is best practice to place all the code bits in the interact method because of this. You also have some other neat methods you can use as well, but that will be for another post =)
So this will be our template that we will begin with. We need to start by asking the user some input so we can validate it.
So there are a few things wrong with the above code. Don’t use it, it’s shit ;p
One of the reasons the above code will not work is what if we wanted to give the user another chance to input something? Also the $errors variable can return the error message instead of of just throwing a new exception.
Let’s see if we can’t refactor this a little better.
Let’s pick this code apart a little as it is just a little different. Instead of using the “ask” method, we changed it to the “askAndValidate” method. This allows us to pass a third argument that is a callback. In this case it will call the new method we added.
This might work for you, but what if you have lots of input you need from the user? Should we just keep making more and more validate functions? Fuck that shit! Let’s refactor again to take advantage of a new php feature =D
This is using the php feature “Anonymous Functions” now. It looks a lot different than most of the code we have written. It does the exact same, but has some added benefits. First off the validation code is right where we can see it. So if we had a command that asked the user 23 different questions, we don’t have to track down code that code either be in other files or somewhere else in the file.
Let’s refactor one more time since we need to get more information from the user and see what else we can do.
Notice the change? In the anonymous functions we are using “use”. This is because the anonymous function will not have access to the “$validator” variable unless we give it access to it.
The code is still a little shitty in my opinion, and I’d love to see what else people come up with.
Questions? Comments? Hit me up =)