Introduction
Building web applications from scratch can be time-consuming and repetitive. PHP Extension and Application Repository (PEAR) is a game-changer and powerful solution, offering a treasure trove of reusable PHP components to streamline your development process. This comprehensive guide delves into the world of PEAR, equipping you with the knowledge to leverage its potential and enhance your coding efficiency.
Table of Contents
What is PEAR?
PEAR stands for PHP Extension and Application Repository. It is a structured library of open-source PHP code. It provides a framework for reusable PHP components. It was developed in 1999 by Stig S. Bakken.
PHP stands for Hypertext Preprocessor. It is a server-side scripting language that can be embedded into HTML, primarily used for web development. Various tools are available as extensions for PHP. For example, the PHP Extension and Application Repository (PEAR) is a package manager for reusable components in PHP.
The purposes of the PEAR are:
- PEAR has a library for PHP users.
- Provide a system for code distribution and package maintenance.
- Provide best practices for PHP development.
- Lead innovation in PHP.
PHP, akin to repositories like CRAN for R and Maven for Java, hosts a structured library of open-source PHP code accessible via the pear.php.net server. Organized into packages, each representing a distinct project with its own development team, versioning, release cycle, and inter-package dependencies, PEAR facilitates code distribution and maintenance. Developers benefit from access to best practices, fostering the creation of secure, reliable, and maintainable code. PEAR is a hub for innovation within the PHP community, with ongoing efforts to enhance the language and develop new extensions and libraries. Additionally, PEAR offers educational resources, including documentation and tutorials, enabling developers to deepen their understanding of PHP and PEAR’s functionalities, making it an invaluable resource for PHP development.
Key Components of PEAR
1. PEAR Base Classes
PEAR has a repository to share and contribute PHP packages for various purposes. PEAR has three classes: PEAR Core Components, PEAR Packages, and PECL Packages. The PEAR package manager is a command line tool that installs and uninstalls packages. It automates the process of resolving dependencies. These are explained as follows in brief.
2. OOPs.
These provide functionality for PHP development. Base classes are for object-oriented programming, error handling, and other basic tasks. These are the basics on which many PEAR packages are built.
3. PEAR Packages
PEAR packages are collections of PHP codes that provide various functionalities and features. They are used in database abstraction, form generation, authentication, caching, encryption, configuration, HTML generation, XML processing, and web services. Each package has PHP source code with documentation and examples.
Installing PEAR
To install PEAR, you need to set up the PEAR infrastructure on your system. It has a PEAR installer for installing, managing, and updating PEAR and PECL packages.
1. The PEAR Installer
The PEAR Installer is a command-line tool. It is used to streamline the process of installing and managing PEAR packages. It comes with PHP installations. So it is readily available for use. The installer automates tasks. For example, you can resolve dependencies, download package files, and configure them for use within your PHP projects.
In Windows:
Open the command prompt in Admin mode. Then, you must navigate to the directory where you installed PHP in the command prompt. Now, execute the following command to save this file in your system:
curl -o go-pear.phar https://pear.php.net/go-pear.phar
Now, run the following command in the same above cmd:
php go-pear.phar
You can install it for the entire system or locally for a particular user in Windows.
As the command prompt suggests, double-click on PEAR_ENV.reg to create its environment variables.
When you click it, then ok:
Note that you need to set environment variables manually if it does not work. Also, there should be a pear.cmd file under your php/pear folder. If you do not find it, then you need to follow the below commands:
- Open a text editor like Notepad.
- Enter the following command and save as pear.bat
@php "%~dp0pearcmd.php" %*
- Place the batch file in the pear directory.
Now you can verify pear in the command prompt using this command:
pear version
Output:
In Unix/Linux/BSD
PEAR Package Manager is usually installed by default with PHP. If not, then you can install using the following commands:
wget http://pear.php.net/go-pear.phar
php go-pear.phar
pear version
In Mac OS X
You can install it using these commands:
curl -O https://pear.php.net/go-pear.phar
php -d detect_unicode=0 go-pear.phar
pear version
Note that you must install PHP before installing PEAR in your system.
2. Basic Usage
It is easy to use the PEAR installer. It has a few basic commands.
Installing a Package
You can install the PEAR package using the “pear install” command. You need to enter the name of the package you want to install. The syntax is:
pear install package-name
For example, you can install HTML_QuickForm2 using the following command:
pear install HTML_QuickForm2
Listing Installed Packages
You can list all installed PEAR packages using the pear list command. For example,
pear list
Updating Packages
You can also update installed packages using the “pear update” command to their latest versions. It can have the most recent features and bug fixes. For example,
pear upgrade-all
Uninstalling Packages
You want to remove a package from your system. Then, you can uninstall it using the “pear uninstall” command. You need to enter that package using this command. The syntax is,
pear uninstall package-name
For example, you can uninstall HTML_QuickForm2 using the following command:
pear uninstall HTML_QuickForm2
3. Alternative Methods
Some other methods for installing PEAR packages are given below.
Composer Integration
Composer is the most used dependency manager for PHP projects. It provides flexibility and features compared to the PEAR Installer. Composer can also manage PEAR packages with other dependencies. So, it is easy to use modern PHP development workflows.
You can download the composer from this location – https://getcomposer.org/download/
You need to download this file and install it on your system.
For example, to install PEAR packages using Composer, you can add the PEAR repository to your composer.json file and require the desired package:
{
"repositories": [
{
"type": "pear",
"url": "https://pear.php.net"
}
],
"require": {
"pear-pear.php.net/mail": "*"
}
}
You can install composer using the “install composer” command.
Manual Installation
You can also opt to install PEAR packages manually. You can download package files from the PEAR repository and extract them into your project directory. But it requires more manual effort. This method may not be as efficient for managing dependencies.
Finding and Using PEAR Packages
You can find and use the PEAR package easily using a centralized PEAR repository and PEAR installer.
1. Browsing the PEAR Repository
You can find PEAR packages by browsing the official PEAR repository. It is a basic way to find PEAR packages. You can visit the PEAR website to find available packages. You can also search by category. There is detailed information about the package, including its purpose, version history, dependencies, and documentation.
2. Installing PEAR Packages
After deciding on your required package, install it using the PEAR Installer. For example, you can install the HTML_QuickForm2 package to generate HTML forms.
pear install HTML_QuickForm2
It fetches the HTML_QuickForm2 package from the PEAR repository and installs it on your system.
3. Including PEAR Packages in Your Projects
After installing a PEAR package, you can use it in your PHP projects. You need to require_once or include_once statements. For example, to use the HTML_QuickForm2 package in your PHP script:
require_once 'HTML/QuickForm2.php';
// The HTML_QuickForm2 package's classes and functions are now usable.
$form = new HTML_QuickForm2('myForm');
4. Managing Dependencies
PEAR packages may depend on other packages. The PEAR Installer automatically resolves and installs these dependencies when you install a package, but you can also manually do this when required.
For example, installing a package that depends on the MDB2 database library. Then you can install this using this command:
pear install MDB2
5. Updating Packages
You can update installed packages to access new features and bug fixes. For example,
pear upgrade-all
6. Finding Package Documentation
PEAR packages provide documentation to understand their usage and functionality. You can find documentation for installed packages using this command:
pear doc package-name
Examples of Popular PEAR Packages
1. Database Abstraction
First, you need to execute this command in administrator mode:
pear install MDB2
You should have installed MySQL with your system’s server and shell.
1. Login to root
Launch the command prompt and type this into it:
mysql -u root -p
Type your root password for the MySQL server and hit enter:
2. Create MySQL Database
Create a database using this command:
CREATE DATABASE example_db;
3. Create MySQL Table
Now, you can create a table inside the example_db database. Use this database:
use example_db;
Then, create a simple table named users with ID, username, and email columns:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);
4. Insert data into the table.
INSERT INTO users (username, email) VALUES
('john_doe', '[email protected]'),
('jane_doe', '[email protected]');
Now, you can use this code to check the output:
database.php
<?php
require_once 'MDB2.php';
// Set your password
$dsn = 'mysql://root:your_password@localhost/example_db';
$options = ['debug' => 2];
$db =& MDB2::factory($dsn, $options);
if (MDB2::isError($db)) {
die("Database connection error: " . $db->getMessage());
}
$query = 'SELECT * FROM users';
$result =& $db->query($query);
if (MDB2::isError($result)) {
die("Query error: " . $result->getMessage());
}
// Start the HTML table
echo '<table border="1">';
echo '<tr><th>id</th><th>username</th><th>email</th></tr>';
// Loop through the query result and output each row in a table row
while ($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
echo '<tr>';
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '</tr>';
}
// Close the HTML table
echo '</table>';
?>
Execute using the command:
php database.php
Output:
Note that most of the PEAR packages work only with PHP 5.3 versions. These packages are deprecated and no longer supported for bug fixes and security updates.
2. HTML Form Generation
The PEAR package includes HTML_QuickForm2. You can install this package and create HTML forms in PHP. You can also create form elements and validation rules using code, reducing the amount of HTML code that needs to be written.
For example, open VS code and write this code:
generate_form.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Set the include path to include the directory where HTML_QuickForm2.php resides
set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\Program Files\php-8.3.3\pear');
// Example of using HTML_QuickForm2 to generate a form
require_once 'HTML\QuickForm2.php';
$form = new HTML_QuickForm2('myForm');
$form->addElement('text', 'username', array(
'label' => 'Username:',
'required' => true
));
$form->addElement('password', 'password', array(
'label' => 'Password:',
'required' => true
));
$form->addElement('submit', null, array(
'value' => 'Submit'
));
echo $form;
?>
Then, you need to install HTML_QuickForm2 using the command:
pear install HTML_QuickForm2
Then, run
php generate_form.php
It will generate HTML code on the terminal:
The above generated code on the terminal is:
<div class="quickform"><form method="post" id="myForm" action="generate_form.php"><div><input type="hidden" id="qf:myForm" name="_qf__myForm" />
<div class="row"><p class="label"></p><div class="element"><input type="text" label="Username:" required="1" name="username" id="username-0" /></div></div>
<div class="row"><p class="label"></p><div class="element"><input type="password" label="Password:" required="1" name="password" id="password-0" /></div></div>
<div class="row"><p class="label"></p><div class="element"><input type="submit" value="Submit" name="" id="qfauto-0" /></div></div></div></form></div>
You need to save this HTML code and open it in a browser. Alternatively, you can also save it as code.html in VS Code. Click on “Go Live” to view the output in the browser:
The output will be:
3. Validator
Validation is an important task when dealing with user input. The following command can be used to install this package:
pear install Validate-0.8.5
Now, you can use this PHP pear code to validate user inputs such as email, number, and date.
validate.php
<?php
require_once('Validate.php'); // Importing Validate class
function ensureParametersOrExit($parameters) {
foreach ($parameters as $parameter) {
// Checking if required parameters are provided
isset($_GET[$parameter]) || exit("Required parameter '$parameter' not provided.");
}
}
// Ensuring required parameters are present
ensureParametersOrExit(['email', 'number', 'date']);
// Creating Validate object
$validator = new Validate();
// Getting email, number and date parameter from GET requests
$email = $_GET['email'];
$number = $_GET['number'];
$date = $_GET['date'];
// Checking if email is valid
if ($validator->checkEmail($email)) {
echo 'Email is valid.<br>';
} else {
echo 'Email is invalid.<br>';
}
// Checking if number is valid
if ($validator->checkNumber($number, ['decimal' => ','])) {
echo 'Number is valid.<br>';
} else {
echo 'Number is invalid.<br>';
}
// Checking if date is valid
if ($validator->checkDate($date, ['format' => '%d-%m-%Y'])) {
echo 'Date is valid.<br>';
} else {
echo 'Date is invalid.<br>';
}
Execute this code using the command:
php validate.php
In this code, we take user input via a GET request and check the validity of the inputs.
The Future of PEAR
Pear is a framework for PHP components. It is similar to the composer. However, PEAR is an old library. Most PEAR packages are not supported by PHP 8. These packages expect PHP version 5.3. Since PEAR has been obsolete and is no longer in use, So, you should avoid using PEAR as a package manager for your new projects. You can use Composer for your new projects. You can use PEAR as a package manager for legacy projects.
Popular PHP PEAR Packages
These are some popular PHP PEAR packages, but they require the version of PHP 5.3.
1. MDB2 (Database Abstraction)
MDB2 provides a database abstraction layer. This layer is used for database interactions, such as connecting to databases, executing queries, fetching results, etc.
2. HTML_QuickForm2 (HTML Form Generation)
It generates HTML form dynamically in PHP. So developers do not need to write more HTML code.
3. Auth (Authentication)
It provides authentication and authorization functionalities for PHP applications. For example, user authentication, session management, access control, etc.
4. Mail (Email Handling)
You can send emails from PHP applications.
Conclusion
PHP PEAR (PHP Extension and Application Repository) is a package manager for PHP code. Developers can organize their code and reuse components. You can install various packages using PEAR. However, it is deprecated and compatible with PHP version 5.3. There is an alternative to PEAR, i.e., Composer. There are various PEAR packages like MDB2 for database abstraction, HTML_QuickForm2 for HTML form generation, Auth for authentication, Mail for email handling, etc. However, note that these packages may require PHP versions 5.3 or earlier.
Frequently Asked Questions (FAQs)
Q1: Can you use PEAR packages with PHP projects developed in modern workflows?
Answer: Yes. You can, but it is older, and some of its packages may require PHP version 5.3 or earlier. Alternatively, PEAR is Composer, which you can use because it is a newer and mostly used PHP package manager.
Q2: How do you manage dependencies between PEAR packages?
Answer: PEAR packages may have dependencies on other PEAR packages. If these do not automatically resolve, you must install them manually.
Q3: Is PEAR still actively maintained and updated?
Answer: No. Many of its packages are deprecated and not actively maintained. The focus has shifted towards modern package managers like Composer.
Recommended Articles
We hope that this EDUCBA information on “PHP PEAR” was beneficial to you. You can view EDUCBA’s recommended articles for more information,