Lesson 15 - Creating libraries in PHP
In the previous exercise, Solved tasks for PHP lesson 14, we've practiced our knowledge from previous lessons.
In the previous lesson, Solved tasks for PHP lesson 14, we learned to declare our own PHP functions. In today's lesson, we're going to gather functions logically into libraries, and test it out on a simple application.
Creating libraries
We usually don't write functions straight into a website, we put them in
separate libraries. A library is nothing more than a file with the
.php
extension where we open a PHP sequence and insert several
functions. A library should, of course, only contain functions that fit its
purpose. We create different libraries for different purposes (for example
emails.php
, math.php
, database.php
...)
and avoid creating "god libraries" for everything in a single file.
Let's create a library for sending e-mails. For now, all it will contain is
the email-sending function that from last time. The contents of
emails.php
will the following:
<?php /* * E-mail library */ function sendEmail($address, $subject, $sender, $message) { $header = 'From:' . $sender; $header .= "\nMIME-Version: 1.0\n"; $header .= "Content-Type: text/html; charset=\"utf-8\"\n"; $success = mb_send_mail($address, $subject, $message, $header); return $success; }
We can add as many functions as we want into a library. For example, we could also add a function that checks whether an e-mail address was filled properly. As you can see, at the end of the code, we don't close the PHP sequence. When all we have in a file is PHP code, the directive is closed automatically when PHP reaches the end of said file. I highly recommend you all not to close the directive since several whitespaces after said closing could cause nasty errors.
Once we finish our library, all we'll have to do is save it to the folder our
website is in and then load it into the files where we need it. We will also
have to use the require()
function to load libraries. We've already
gone over what it does in previous lessons, it inserts the contents of a file
and executes PHP sequences (if there are any). In our case, it'll include the
functions declared in our library. To make sure that we don't re-load a library,
we'll use the require_once()
function. This function prevents a
library from being loaded again, which would lead to errors. Since we are
displaying the entire website using index.php
, we will only load
libraries from one specific location. If our website was split up into multiple
pages, we would have to load the libraries in each of the documents where we
need them.
require_once('emails.php'); sendEmail('[email protected]', 'E-mail test', '[email protected]', 'Message text');
At this point, the function has been declared in our library and all we have left to do is load it. If you stick to this approach, your applications will be very readable. Let's make a library that does several things with strings.
Sentence analyzer
Let's program a simple sentence analyzer that takes a sentence as a parameter. The sentence analyzer will print the number of characters in the sentence, the number of vowels, and the number of the other characters.
Library
Let's get right to it! We know that we use the mb_strlen()
function to determine the number of characters in a string. However, PHP won't
be able to count vowels and consonants for us, so we'll have our library do it
for us. We'll name it sentenceAnalyzer.php
. Its contents will be as
follows:
<?php /** * Sentence analyzing library */ function countConsonants($text) { $text = mb_strtoupper($text); $length = mb_strlen($text); $consonants = array('A', 'E', 'I', 'O', 'U', 'Y'); $count = 0; for ($i = 0; $i < $length; $i++) { $character = mb_substr($text, $i, 1); if (in_array($character, $consonants)) $count++; } return $count; } function countVowels($text) { $text = mb_strtoupper($text); $length = mb_strlen($text); $vowels = array('B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z'); $count = 0; for ($i = 0; $i < $length; $i++) { $character = mb_substr($text, $i, 1); if (in_array($character, $vowels)) $count++; } return $count; }
Each function defines the variables $text
and
$length
, where the text and its length are stored. It stores the
characters that are to be counted and stored into the
$vowels
/$consonants
array. It creates a
$count
variable and initializes it with a value of 0
.
Then, it iterates over the characters using a loop and stores the current
character into a variable with the same name ($character
). With the
help of the in_array()
function, it determines whether the array
contains this character. If it does, the counter's value is increased. Then, all
it would have to do is return the result value.
As you may have noticed, the functions are identical except for the array
values. We could optimize the code significantly by creating a single universal
function, that takes a string and an array as inputs. We'll call this function
from both the countVowels()
and countConsonants()
functions.
The same exact functionality can be achieved with this code:
<?php /** * Sentence analyzing library */ function countCharacters($text, $characters) { $text = mb_strtoupper($text); $length = mb_strlen($text); $count = 0; for ($i = 0; $i < $length; $i++) { $character = mb_substr($text, $i, 1); if (in_array($character, $characters)) $count++; } return $count; } function countVowels($text) { $vowels = array('A', 'E', 'I', 'O', 'U', 'Y'); return countCharacters($text, $vowels); } function countConsonants($text) { $consonants = array('B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z'); return countCharacters($text, $consonants); }
We have now split the task up into 3
functions. As you can see,
functions are our allies and can make our life much simpler. We could now call
the same function with different parameters instead of having to copy the whole
thing over and over again.
Now, let's create an analyze.php
file where we'll insert an
input form for the sentence, load the library, and determine character
counts:
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Sentence analyzer</title> </head> <body> <h1>Sentence analyzer</h1> <?php require_once('sentenceAnalyzer.php'); if ($_POST) { if (isset($_POST['message'])) { $message = $_POST['message']; $characters = mb_strlen($message); $vowels = countVowels($message); $consonants = countConsonants($message); echo('<h2>Analysis result:</h2>'); echo('<table>'); echo('<tr><td>Characters</td><td>' . htmlspecialchars($characters) . '</td></tr>'); echo('<tr><td>Vowels</td><td>' . htmlspecialchars($vowels) . '</td></tr>'); echo('<tr><td>Consonants</td><td>' . htmlspecialchars($consonants) . '</td></tr>'); echo('</table>'); } } ?> <p>Enter the sentence to be analyzed</p> <form method="post"> <textarea name="message"></textarea><br /> <input type="submit" value="Analyze" /> </form> </body> </html>
The result:
Imagine how the source code would be without the help of functions (it would look god awful, trust me). We usually use folders to store libraries when there's more than one of them.
Generally, it's a good thing to store most of the application logic in libraries or objects, which we will get into soon enough. Try to minimize the amount of PHP in files that actually have HTML pages in them. This way, we separate the logic from the output (presentation). Later, we'll learn about the MVC architecture, where the logic/presentation principle is brought to perfection. We'll continue with functions and libraries in the PHP database course.
Where to go next?
You now know enough to start working with databases, follow this link to continue: Databases in PHP for beginners. See you on the other side!
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 51x (1.84 kB)
Application includes source codes in language PHP