Monday 12 June 2017

quickly test php snippets

Have you ever wanted to quickly test small PHP snippets of code, but you became bogged down in opening up your favorite IDE, preparing a simple test.php file, loading it in the browser, etc.? Sometimes, all you want to do is quickly test some logic. Perhaps you’re even just browsing some of the example snippets at the PHP online manual, and thought it might be nice to just quickly run these examples and see them in action. Maybe you want to try refactoring a few things and see how it goes. Sometimes, your everyday workflow is overkill for these simple situations. There is a perfect solution for you however, I give you: PHP Console!

Created by Jordi Boggiano

Now the PHP Console is created by Jordi Boggiano. Jordi is the creator of Composer. Composer has single handedly revolutionized the PHP landscape, so we know this PHP Console is a nice little piece of software. When you visit the github page, you will see there are steps to install the php debug console and it is pretty straight forward.

Install The PHP Debug Console

For this example, we simply installed it in C:\wamp\www\console by typing composer require seld/php-console from the www directory.
You can also find the console on packagist right here.

Testing PHP Console

Once we have the php console installed, we can test it out by visiting http://localhost/console/vendor/seld/php-console/.
Cool! Note that you are given a simple text area where you can write some simple snippets of PHP, then simply click the Try this! button to execute the code. Just above the text area is the code result output. If you’re so lazy that you can’t even bring yourself to click a button to run your code, you also have the option to press ctrl-enter to run your snippet. It’s a great little learning tool to have, and a fantastic way to test out quick snippets of code without all the overhead. Maybe you’re just learning about a specific function in PHP such as the substr php function. Now you can test it out very easily. Let’s see!
Imagine this code.
Off the top of your head, you probably forget what this even does. No problem, plug it into the console and test it out.
Maybe you’d like to put the array_unique function to the test. Also, very easy to do. First let’s look at the code, then give it a test run in the PHP Console.
We input the code into the text area and click Try It! Notice that the array_unique() function does in fact remove any duplicates and the output looks good. How about creating our own function right in the testing area. Will it work? Let’s try it out.
A very common thing in PHP is to check if a string contains a specific word. Said another way, you will often need to check for the occurrence of one string inside of another. The strpos() function can be used for this. Using this knowledge, let’s create a function that is a little more user friendly. Here is the code we have come up with.
Pretty cool! We were able to create our own function named findOccurrence() which accepts two parameters. The first is a haystack we will search through and the second is the needle we will be looking for. Inside of our findOccurrence() function, we use strpos() to do the heavy lifting for us. This is what is known as a wrapper function. We can make use of wrappers to customize how we would like to interact with the language. In the example above we can see that one string definitely does exist within the other string of We can find an occurrence of one string inside other. Let’s change the needle we are looking for and see what happens.
This time around we look for Gwen. When we run our function, we can see that it is working correctly since it reports back to us that Gwen is not in the haystack. Shame, we love Gwen.

What about connecting to a database?

When using the PHP Console tool, you can even connect to a database if you like to test out snippets involving database queries. We have a database on the same localhost as our PHP installation. The database name is “pdotest” and we’ll just log in as root with no password. Let’s try it out!
Now that we know we can connect to the database, let’s try to create a table. The database pdotest is currently empty, but we’ll create a table to hold a few links. Let’s create a table in our database using PDO.
With a table now created, we can complete an insert statement using PDO. Let’s insert a link into our new table. We’ll insert a link for Google.
Now that we have inserted a link using PDO, let’s try to fetch it out of the database to see if it worked. We’ll use a prepared statement to test this.
Pretty Cool! This seems to be working great! Let’s now add another link to the database, but this time we’ll make use of a prepared statement for the insert as well. We will add Twitter this time.
We get back a boolean true which means it worked. Let’s fetch the records again and see what we get!
It definitely looks like it is working, but notice the duplication of data. This is because by default, the fetchAll() method in PDO will return the data in two forms. One as an indexed array, and another as an associative array. This actually works out pretty good, because it gives you the flexibility to interact with that data however you might like. Another way to make this work is to tell PDO that you would like objects to work with instead. Let’s see how.
Now it would be easy for example to say you want the href of the second link in the database. To do this, you could use this snippet in the php debug console.

PHP Psysh and Laravel Tinker

Another method of interacting with PHP at the console is via Psysh. If you use the Laravel framework, you might be familiar with Tinker which is powered by Psysh. This tool is officially a REPL or read eval print loop. It makes it possible for you to run PHP code directly in the console. Let’s try setting up an index based array in Psysh(Tinker in this case). Do note, that first you must enter the shell by typing php artisan tinker which will give you the following output: Psy Shell v0.7.2 (PHP — cli) by Justin Hileman.
Now that we have a simple index based array of data, we can inspect it just like we would expect. Here we test the data with a print_r() and var_dump() of the array.
Let’s test out the commonly used in_array() function which tests to see if a given value is in an array.
Let’s now quickly create an object to work with in PHP. The quickest way to create an object to work with in PHP without having to rely on a class is to simply cast an array to an object. Let’s see how we might do this.
Notice that in this case we are simply assigning an associative array to a variable, but just preceding the array brackets is the (object) cast to operator. This takes our associative array and converts it to an object. Notice how it gets output to the screen right away. From there, we can access individual properties of the object just like we normally would. All of this is making use of the stdClass built in to PHP. We can even create a new class in the REPL and test out its functionality. Let’s create a simple Task class right in the console and complete a task.
Even though the repl only works one line at a time, you can still hit the enter key and go to a new line, continuing to input code. What you will see is that the prompt changes from three greater than signs to three dots. This indicates that the console recognizes you are not finished entering valid PHP code, and you need to finish typing. The first example of this is where we begin to define our Task class. Notice the three dots on each new line right up until we finally complete the last closing brace of the class. At that point, null is output to the screen and we get our standard prompt back. At this point, we have a new class defined in memory. We can now make use of it! We create a new task to Clean Desk. We then inspect the completed property and see that it is false. Then we make a call to the finish() method and complete the task. A final inspection of the completed property shows us that this is now true. Pretty cool! This type of simple test and run code at a console is great practice to hone your syntax chops without the help of an IDE to guide you along.

How To Quickly Test PHP Snippets Summary

In this tutorial we covered the php debug console. We found that it is a great tool to have when you just want to test out quick snippets of PHP code. It makes the process easier since you can avoid the overhead of firing up your IDE and switching between the IDE and browser window along with the constant window refreshes. Sometimes you just want to quickly test the behavior of any number of string functions, or array functions, test out objects, or even work with a database like we did here. It’s a nice tool to have at your disposal. Have fun!