Introduction to PHP Frameworks
What are PHP Frameworks?
PHP frameworks are pre-written code libraries that provide a foundation for building web applications. They offer a structured way to organize code, implement common functionality, and follow best practices. Frameworks help developers build applications faster, more securely, and with better maintainability.
Benefits of Using PHP Frameworks
1. Rapid Development
Frameworks provide pre-built components and tools that speed up development time significantly.
<?php
// Without framework - manual routing
if ($_GET['page'] == 'users' && $_GET['action'] == 'show') {
include 'show_user.php';
}
// With framework - clean routing
Route::get('/users/{id}', 'UserController@show');
?>
2. Security Features
Most frameworks include built-in security features like CSRF protection, SQL injection prevention, and XSS filtering.
3. Code Organization
Frameworks enforce structured architecture patterns like MVC (Model-View-Controller).
4. Community Support
Popular frameworks have large communities, extensive documentation, and third-party packages.
5. Testing Support
Frameworks typically include testing tools and follow testable architecture patterns.
Common Framework Features
MVC Architecture
Most PHP frameworks implement the Model-View-Controller pattern:
<?php
// Model - handles data logic
class User extends Model {
public function findByEmail($email) {
return $this->where('email', $email)->first();
}
}
// Controller - handles business logic
class UserController extends Controller {
public function show($id) {
$user = User::find($id);
return view('users.show', compact('user'));
}
}
// View - handles presentation
// users/show.blade.php
?>
Object-Relational Mapping (ORM)
Frameworks provide ORM systems for database interactions:
<?php
// Raw SQL
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
// ORM
$user = User::where('email', $email)->first();
?>
Routing Systems
Clean URL routing with parameter binding:
<?php
// Route definitions
Route::get('/users', 'UserController@index');
Route::get('/users/{id}', 'UserController@show');
Route::post('/users', 'UserController@store');
Route::put('/users/{id}', 'UserController@update');
Route::delete('/users/{id}', 'UserController@destroy');
?>
Popular PHP Frameworks
Full-Stack Frameworks
Laravel
Laravel is the most popular PHP framework, known for its elegant syntax and rich feature set.
Key Features:
- Eloquent ORM
- Blade templating
- Artisan CLI
- Queue system
- Real-time broadcasting
Best For:
- Rapid application development
- Modern web applications
- API development
- Large-scale applications
# Install Laravel
composer create-project laravel/laravel myapp
Symfony
Symfony is a mature, enterprise-focused framework with reusable components.
Key Features:
- Reusable components
- Doctrine ORM
- Twig templating
- Console component
- Strong testing support
Best For:
- Enterprise applications
- Long-term projects
- Complex business logic
- High-performance applications
# Install Symfony
composer create-project symfony/skeleton myapp
CakePHP
CakePHP follows convention over configuration and provides rapid development tools.
Key Features:
- Convention over configuration
- Built-in ORM
- Code generation
- Extensive plugins
- Strong security features
Best For:
- Rapid prototyping
- Small to medium applications
- Developers new to frameworks
# Install CakePHP
composer create-project cakephp/app myapp
Micro Frameworks
Slim Framework
Slim is a lightweight framework perfect for APIs and microservices.
Key Features:
- Minimal overhead
- PSR-7 compliant
- Middleware support
- Dependency injection
- Easy routing
Best For:
- API development
- Microservices
- Simple web applications
<?php
use Slim\Factory\AppFactory;
$app = AppFactory::create();
$app->get('/users/{id}', function ($request, $response, $args) {
$userId = $args['id'];
// Fetch user logic
return $response->withJson(['user' => $user]);
});
$app->run();
?>
Lumen
Lumen is Laravel's micro-framework for microservices and APIs.
Key Features:
- Laravel components
- Fast performance
- Minimal configuration
- Easy to scale up to Laravel
Best For:
- Microservices
- API development
- Performance-critical applications
Framework Comparison
Framework | Learning Curve | Performance | Community | Best Use Case |
---|---|---|---|---|
Laravel | Medium | Good | Very Large | Full-stack web apps |
Symfony | High | Excellent | Large | Enterprise applications |
CodeIgniter | Low | Good | Medium | Beginner-friendly projects |
CakePHP | Medium | Good | Medium | Rapid development |
Slim | Low | Excellent | Medium | APIs and microservices |
Zend/Laminas | High | Excellent | Medium | Enterprise applications |
Choosing the Right Framework
Consider Your Project Requirements
Project Size and Complexity
<?php
// Small project - Consider Slim or CodeIgniter
class SimpleAPI {
public function getUsers() {
// Simple logic
}
}
// Large enterprise project - Consider Symfony or Laravel
class ComplexApplication {
private $userService;
private $permissionService;
private $auditService;
public function handleUserRequest($request) {
// Complex business logic with multiple services
}
}
?>
Team Experience
- Beginners: CodeIgniter, CakePHP
- Experienced: Laravel, Symfony
- Mixed teams: Laravel (good documentation and community)
Performance Requirements
- High performance: Slim, Symfony
- Moderate performance: Laravel, CakePHP
- Performance + features: Symfony
Long-term Maintenance
- Long-term projects: Symfony, Laravel
- Quick prototypes: CodeIgniter, Slim
Framework Architecture Patterns
MVC Pattern Implementation
<?php
// Model Layer
class UserModel {
private $db;
public function __construct($database) {
$this->db = $database;
}
public function getAllUsers() {
return $this->db->query("SELECT * FROM users")->fetchAll();
}
public function getUserById($id) {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
}
// View Layer
class UserView {
public function render($template, $data = []) {
extract($data);
include "templates/{$template}.php";
}
}
// Controller Layer
class UserController {
private $model;
private $view;
public function __construct(UserModel $model, UserView $view) {
$this->model = $model;
$this->view = $view;
}
public function index() {
$users = $this->model->getAllUsers();
$this->view->render('users/index', ['users' => $users]);
}
public function show($id) {
$user = $this->model->getUserById($id);
$this->view->render('users/show', ['user' => $user]);
}
}
?>
Modern Framework Features
Dependency Injection
<?php
// Container setup
$container = new Container();
$container->bind('Database', function() {
return new PDO('mysql:host=localhost;dbname=app', $user, $pass);
});
$container->bind('UserService', function($container) {
return new UserService($container->get('Database'));
});
// Automatic injection in controllers
class UserController {
public function __construct(
private UserService $userService,
private LoggerInterface $logger
) {}
public function index() {
$users = $this->userService->getAllUsers();
$this->logger->info('Users fetched');
return view('users.index', compact('users'));
}
}
?>
Middleware
<?php
// Authentication middleware
class AuthMiddleware {
public function handle($request, $next) {
if (!$request->user()) {
return redirect('/login');
}
return $next($request);
}
}
// CORS middleware
class CorsMiddleware {
public function handle($request, $next) {
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
return $response;
}
}
// Using middleware
Route::middleware(['auth', 'cors'])->group(function() {
Route::get('/dashboard', 'DashboardController@index');
Route::resource('/users', 'UserController');
});
?>
Event Systems
<?php
// Event definition
class UserRegistered {
public function __construct(
public readonly User $user
) {}
}
// Event listener
class SendWelcomeEmail {
public function handle(UserRegistered $event) {
Mail::to($event->user->email)
->send(new WelcomeEmail($event->user));
}
}
// Event dispatcher
class UserService {
public function register($userData) {
$user = User::create($userData);
// Dispatch event
event(new UserRegistered($user));
return $user;
}
}
?>
Getting Started with Frameworks
Setup and Installation
# Using Composer for most frameworks
composer create-project framework-name/skeleton project-name
# Laravel
composer create-project laravel/laravel myapp
cd myapp
php artisan serve
# Symfony
composer create-project symfony/skeleton myapp
cd myapp
symfony server:start
# Slim
composer create-project slim/slim-skeleton myapp
cd myapp
php -S localhost:8000 -t public
Basic Project Structure
project/
├── app/
│ ├── Controllers/
│ ├── Models/
│ ├── Services/
│ └── Middleware/
├── config/
├── public/
│ └── index.php
├── resources/
│ ├── views/
│ └── assets/
├── routes/
├── storage/
├── tests/
├── vendor/
└── composer.json
Development Workflow
<?php
// 1. Define routes
Route::get('/users', 'UserController@index');
// 2. Create controller
class UserController extends Controller {
public function index() {
$users = User::all();
return view('users.index', compact('users'));
}
}
// 3. Create model
class User extends Model {
protected $fillable = ['name', 'email'];
public function posts() {
return $this->hasMany(Post::class);
}
}
// 4. Create view
@extends('layouts.app')
@section('content')
@foreach($users as $user)
<div>{{ $user->name }}</div>
@endforeach
@endsection
?>
Best Practices
1. Follow Framework Conventions
Each framework has its own conventions - follow them for consistency and community support.
2. Use Dependency Injection
<?php
// Good - Injectable dependencies
class UserService {
public function __construct(
private UserRepository $repository,
private EmailService $emailService
) {}
}
// Avoid - Hard dependencies
class UserService {
public function sendEmail() {
$mailer = new PHPMailer(); // Hard dependency
}
}
?>
3. Leverage Framework Features
<?php
// Use framework's validation
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|min:8'
]);
// Use framework's pagination
$users = User::paginate(15);
// Use framework's caching
Cache::remember('users', 3600, function() {
return User::all();
});
?>
4. Write Tests
<?php
class UserControllerTest extends TestCase {
public function test_can_list_users() {
$response = $this->get('/users');
$response->assertStatus(200)
->assertSeeText('Users List');
}
public function test_can_create_user() {
$userData = [
'name' => 'John Doe',
'email' => '[email protected]'
];
$response = $this->post('/users', $userData);
$response->assertStatus(201);
$this->assertDatabaseHas('users', $userData);
}
}
?>
PHP frameworks provide powerful tools for building modern web applications. Choose the framework that best fits your project requirements, team expertise, and long-term goals. Remember that learning one framework well is often better than knowing many frameworks superficially.