Topic 9: Using Other Open-Source Material
📖 13 min read · 🎯 Advanced · 🧭 Prerequisites: data-base-structuring-table-designing, javascript-object
Why this matters
Here's the thing — when you start building with PHP, your first instinct might be to write everything yourself. But out there, thousands of developers have already solved the exact problems you're facing, and they've shared that work freely as open-source libraries. Tools like Smarty, Laravel, and PHPUnit exist so you don't start from zero every time. In this lesson, I'll show you how to find these libraries and pull them into your project using Composer — a skill that will save you hours on every project you build.
What You'll Learn
- Why open-source libraries accelerate PHP development and where to find them
- How to install and configure the Smarty template engine via Composer
- How to scaffold, route, and render views in a Laravel project
- How to write and run automated tests with PHPUnit
The Analogy
Think of open-source libraries like a fully stocked municipal tool library in Vizag. Instead of forging your own hammer every time you need to drive a nail, you walk to the library, check out a professional-grade tool, use it, and put it back. The tool was built by expert craftspeople, maintained by volunteers, inspected by thousands of prior borrowers, and costs you nothing but a library card — in our case, a single composer require command. Smarty is the precision drafting table, Laravel is the power workshop with every tool pre-arranged, and PHPUnit is the quality-control inspector who checks every joint before the building opens.
Chapter 1: Why Use Open-Source Materials?
Open-source resources — libraries, frameworks, and toolkits — offer four core advantages over rolling your own:
- Cost-Effective — Free to use, modify, and distribute. No licensing fees, no vendor lock-in.
- Community Support — Large communities provide extensive documentation, tutorials, Stack Overflow answers, and issue trackers.
- Quality and Security — Often rigorously tested and maintained by many contributors; security patches arrive fast.
- Innovation — Access to cutting-edge technology and features that would take months to build from scratch.
Where to Find Open-Source PHP Material
Three canonical platforms for discovering PHP packages:
| Platform | Purpose |
|---|---|
| Packagist | The default package repository for Composer — search by name or keyword |
| GitHub | Hosts source code for virtually every major PHP project; read issues, PRs, and READMEs |
| SourceForge | Legacy repository still hosting many mature open-source PHP tools |
Composer ties all of this together. When you run composer require vendor/package, Composer resolves the dependency graph, downloads the correct versions, and wires up PSR-4 autoloading automatically via vendor/autoload.php.
Chapter 2: Example 1 — Smarty Template Engine
Smarty separates the presentation layer (HTML templates) from the business logic layer (PHP). Controllers assign variables; templates render them — no PHP tags cluttering your HTML.
Step 1: Install Smarty via Composer
composer require smarty/smarty
Step 2: Create the Directory Structure
my_project/
├── templates/
│ └── index.tpl
├── templates_c/
└── index.php
templates/ holds your .tpl source files. templates_c/ is where Smarty writes its compiled PHP cache — keep it writable.
Step 3: Create the Template File (templates/index.tpl)
<!DOCTYPE html>
<html>
<head>
<title>{$title}</title>
</head>
<body>
<h1>{$heading}</h1>
<p>{$content}</p>
</body>
</html>
Smarty variables are wrapped in {$variable} syntax. Nothing else runs in the template by default — that's the point.
Step 4: Create the PHP Controller (index.php)
<?php
require 'vendor/autoload.php';
$smarty = new Smarty;
$smarty->setTemplateDir('./templates');
$smarty->setCompileDir('./templates_c');
$smarty->assign('title', 'Smarty Example');
$smarty->assign('heading', 'Hello, Smarty!');
$smarty->assign('content', 'This is a simple example of using Smarty.');
$smarty->display('index.tpl');
?>
assign() binds a PHP value to a template variable. display() compiles the template (on first run) and sends the rendered HTML to the browser.
Step 5: Run the Built-in Dev Server
php -S localhost:8000
Open http://localhost:8000 — you'll see the rendered page with all three assigned values interpolated.
Chapter 3: Example 2 — Laravel Framework
Laravel is a full-stack PHP framework known for its elegant syntax, built-in routing, Eloquent ORM, Blade templating, and robust ecosystem.
Step 1: Scaffold a New Laravel Project
composer create-project --prefer-dist laravel/laravel my_laravel_project
Composer downloads Laravel and all its dependencies into my_laravel_project/.
Step 2: Enter the Project Directory
cd my_laravel_project
Step 3: Start the Development Server
php artisan serve
Visit http://localhost:8000 — the default Laravel welcome page confirms the installation is working.
Step 4: Add a Custom Route
Edit routes/web.php:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome', ['name' => 'Laravel']);
});
Route::get() registers a GET route. view('welcome', [...]) renders resources/views/welcome.blade.php and passes the $name variable into it.
Step 5: Update the Blade View
Edit resources/views/welcome.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to {{ $name }}</title>
</head>
<body>
<h1>Hello, {{ $name }}!</h1>
</body>
</html>
Blade's {{ $variable }} syntax HTML-escapes output automatically, preventing XSS. Refresh http://localhost:8000 to see "Hello, Laravel!" rendered in the browser.
sequenceDiagram
participant Browser
participant Laravel Router
participant Controller (Closure)
participant Blade Engine
Browser->>Laravel Router: GET /
Laravel Router->>Controller (Closure): matches route
Controller (Closure)->>Blade Engine: view('welcome', ['name'=>'Laravel'])
Blade Engine-->>Browser: rendered HTML
Chapter 4: Example 3 — PHPUnit for Testing
PHPUnit is the standard testing framework for PHP. It lets you write assertions about your code's behaviour and run them automatically — catching regressions before they reach production.
Step 1: Install PHPUnit as a Dev Dependency
composer require --dev phpunit/phpunit
--dev keeps PHPUnit out of your production vendor/ bundle.
Step 2: Create the Source and Test Directory Structure
my_project/
├── src/
│ └── Calculator.php
└── tests/
└── CalculatorTest.php
Step 3: Write the Class Under Test (src/Calculator.php)
<?php
class Calculator {
public function add($a, $b) {
return $a + $b;
}
}
Step 4: Write the Test File (tests/CalculatorTest.php)
<?php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase {
public function testAdd() {
$calculator = new Calculator();
$result = $calculator->add(2, 3);
$this->assertEquals(5, $result);
}
}
testAdd instantiates Calculator, calls add(2, 3), and asserts the result equals 5. If it doesn't, PHPUnit reports a failure with a diff of expected vs. actual.
Step 5: Run the Test Suite
vendor/bin/phpunit tests
A green . for each passing test; F for a failure; E for an error. A passing run prints something like:
OK (1 test, 1 assertion)
🧪 Try It Yourself
Task: Wire up a Smarty-powered "About Me" page.
- Follow Steps 1–5 from Chapter 2 to install Smarty and create the directory structure.
- In
templates/index.tpl, add a fourth variable{$author}inside a<footer>tag. - In
index.php, add$smarty->assign('author', 'Your Name');. - Run
php -S localhost:8000and open the browser.
Success criterion: You should see your name appear in the page footer alongside the title, heading, and content — all rendered without a single PHP tag in the template file.
Starter snippet for index.php:
<?php
require 'vendor/autoload.php';
$smarty = new Smarty;
$smarty->setTemplateDir('./templates');
$smarty->setCompileDir('./templates_c');
$smarty->assign('title', 'About Me');
$smarty->assign('heading', 'Welcome to My Page');
$smarty->assign('content', 'Learning Smarty in Vizag.');
$smarty->assign('author', 'Your Name'); // add this
$smarty->display('index.tpl');
?>
🔍 Checkpoint Quiz
Q1. What is Packagist and what role does it play in PHP open-source development?
A) A PHP testing framework for writing unit tests
B) The default package repository that Composer searches when you run composer require
C) A built-in PHP function for loading class files automatically
D) A Blade templating compiler bundled with Laravel
Q2. Given this routes/web.php snippet:
Route::get('/', function () {
return view('welcome', ['name' => 'Laravel']);
});
What does the second argument to view() do?
A) Sets the HTTP response status code
B) Passes the $name variable into the Blade template as {{ $name }}
C) Specifies which controller method to call
D) Defines the route middleware stack
Q3. Read the PHPUnit test below. What will happen if Calculator::add() is changed to return $a - $b?
public function testAdd() {
$calculator = new Calculator();
$result = $calculator->add(2, 3);
$this->assertEquals(5, $result);
}
A) The test passes because subtraction is the inverse of addition
B) The test is skipped because the method signature didn't change
C) The test fails — PHPUnit reports expected 5 but got -1
D) The test errors out because assertEquals only works with strings
Q4. You're building a PHP project and need a library that sends transactional email. How would you find and install it using the open-source workflow taught in this lesson?
A) Search Packagist for an email library, run composer require vendor/package, then require 'vendor/autoload.php' in your PHP file
B) Download a ZIP from GitHub and manually copy files into your project root
C) Add the library to routes/web.php using a Route::library() directive
D) Write a PHPUnit test first and let the framework auto-install the dependency
A1. B — Packagist is the default package repository Composer queries. When you run composer require, Composer resolves metadata and download URLs from Packagist.
A2. B — The second argument is an associative array. Laravel's view() helper extracts it into the template scope, making $name available as {{ $name }} in Blade.
A3. C — add(2, 3) would return 2 - 3 = -1, which does not equal 5. PHPUnit marks the test as a failure and shows the diff: Expected: 5 / Actual: -1. This is exactly the regression-catching behaviour automated tests are designed for.
A4. A — The standard open-source PHP workflow is: discover on Packagist → composer require vendor/package → autoload via require 'vendor/autoload.php'. Manual ZIP copying bypasses Composer's dependency resolution and autoloading.
🪞 Recap
- Open-source libraries are free, community-backed, and battle-tested — they accelerate PHP projects on four axes: cost, support, quality, and innovation.
- Packagist, GitHub, and SourceForge are the canonical places to discover PHP packages; Composer is the tool that installs and autoloads them.
- Smarty separates HTML templates from PHP logic using
{$variable}placeholders, installed withcomposer require smarty/smarty. - Laravel scaffolds a full-stack application in one command (
composer create-project) and uses Blade's{{ $variable }}syntax for safe, auto-escaped output. - PHPUnit, installed as a dev dependency with
composer require --dev phpunit/phpunit, lets you assert expected behaviour and catch regressions automatically withvendor/bin/phpunit.
📚 Further Reading
- Composer official docs — the source of truth for dependency management, version constraints, and autoloading
- Smarty Template Engine docs — full reference for Smarty variables, modifiers, and plugins
- Laravel documentation — covers routing, Blade, Eloquent ORM, middleware, and every other framework feature
- PHPUnit documentation — complete guide to assertions, test doubles, fixtures, and coverage reports
- Packagist — browse and search the PHP package ecosystem
- ⬅️ Previous: JavaScript Object
- ➡️ Next: JavaScript Map Object