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 inC:\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 visitinghttp://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.
1
2
3
|
<?php
echo substr('PHP console is great', 4).'<br>';
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php
$array = [
'Time for a sandwich',
'Time for a sandwich',
'PHP 7 is great',
'PHP 7 is great',
'All about that bass, no treble',
'All about that bass, no treble',
];
$unique = array_unique($array);
foreach ($unique as $u) {
echo $u . '<br>';
}
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php
function findOccurrence($haystack, $needle)
{
if (strpos($haystack, $needle) !== false) {
return true;
} else {
return false;
}
}
$haystack = "We can find an occurrence of one string inside other";
$needle = "one string";
if (findOccurrence($haystack, $needle)) {
echo '<em>' . $needle . '</em> is in the haystack';
} else {
echo '<em>' . $needle . '</em> is not in the haystack';
}
|
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!
1
2
3
4
|
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');
var_dump($dbh);
|
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.
1
2
3
4
5
6
7
8
|
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');
$sql = 'CREATE table links(ID INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR( 50 ) NOT NULL, href VARCHAR( 50 ) NOT NULL);';
$results = $dbh->exec($sql);
var_dump($results);
|
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.
1
2
3
4
5
6
7
|
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');
$sql = 'insert into links(name, href) values("Google", "http://google.com");';
$results = $dbh->exec($sql);
var_dump($results);
|
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.
1
2
3
4
5
6
7
8
|
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');
$statement = $dbh->prepare('select * from links');
$statement->execute();
var_dump($statement->fetchAll());
|
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.
1
2
3
4
5
6
7
8
|
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');
$statement = $dbh->prepare('insert into links(name, href) values("Twitter", "http://twitter.com");');
$result = $statement->execute();
var_dump($result);
|
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.
1
2
3
4
5
6
7
8
|
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');
$statement = $dbh->prepare('select * from links');
$statement->execute();
var_dump($statement->fetchAll(PDO::FETCH_OBJ));
|
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.
1
2
3
4
5
6
7
8
9
10
|
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');
$statement = $dbh->prepare('select * from links');
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_OBJ);
echo $results[1]->href;
|
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 typingphp artisan tinker
which will give you the following output: Psy Shell v0.7.2 (PHP 7.0.5-3+donate.sury.org~trusty+1 — 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.
0 comments: