Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 147 ยท Modern PHP and Ecosystem

PHP Frameworks and CMSs

What PHP frameworks give you, how MVC works (with a tiny runnable MVC app), and how Laravel, Symfony, Slim, WordPress and Drupal compare so you can choose well.

Every web application needs the same plumbing: map URLs to code, read and validate input, talk to a database, render HTML safely, handle sessions and logins, send email, run background jobs, log errors. You can build all of that yourself, and earlier lessons showed you how each piece works. But for real projects, almost everyone uses a framework: a collection of well-tested components plus conventions for how an application is organized.

This lesson explains what frameworks give you, then builds a tiny MVC application in plain PHP so you can see the architecture most frameworks share. After that you'll tour the major PHP frameworks (Laravel, Symfony and the lighter options), the content management systems (WordPress, Drupal) and how to choose between them. Knowing the plain-PHP foundations first, as you do now, is what makes framework code readable instead of magical.

What a framework gives you

A full-stack PHP framework typically includes:

  • Routing: map GET /posts/42 to a controller method (Front Controllers and Routing).
  • Controllers and middleware: organize request handling, with reusable steps such as authentication, CSRF checks and rate limiting wrapped around every request.
  • An ORM or database layer: query builders, models, relationships, migrations (PHP and Databases).
  • Templates with automatic escaping, so forgetting htmlspecialchars() can't create an XSS hole (Preventing XSS).
  • Validation, forms, sessions, authentication, authorization and CSRF protection built in.
  • A dependency injection container that wires your classes together (Design Patterns in PHP).
  • Queues, scheduling, caching, mail, events, logging and a command-line tool for generating code and running tasks (Command-Line PHP).
  • Testing helpers: simulated HTTP requests, database factories, fakes for mail and queues (Testing PHP Code).

The biggest benefit isn't any single feature. It's that thousands of developers have already found and fixed the security bugs, edge cases and performance problems in that code, and that a new team member who knows the framework can find their way around your project on day one.

MVC: Model, View, Controller

Most PHP frameworks organize code with the Model-View-Controller pattern:

  • The model holds the data and the rules about it: loading and saving records, validating values, business logic. It knows nothing about HTTP or HTML.
  • The view turns data into output, usually HTML. It contains presentation logic only: loops, formatting and escaping.
  • The controller handles one request: it reads input, asks models for data or tells them to change, and picks a view to render the response.

A front controller (public/index.php) receives every request and hands it to a router, which picks the controller. Let's build each part in plain PHP. Because our editor has no web server, each example simulates a request by calling the application with a method and a path, which is exactly what framework test helpers do too.

The model

The model wraps the database. Here it uses PDO with an in-memory SQLite database (PDO Basics) and returns plain arrays:

PHP The model layer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Creating the table in the constructor is only for this demo; a real application creates tables with migrations. Notice that the model never prints anything and never looks at $_GET. That separation is what lets you reuse it from a web page, an API endpoint or a command-line import.

The view

A view is a template that receives data and returns HTML. This one uses output buffering (ob_start()) to capture a template written in PHP's alternative syntax, and an e() helper that escapes every value, the same approach as PHP and HTML Templates:

PHP The view layer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is HTML source shown as text; on a web server the browser would render it as a heading and a list of links. The title containing <escape> comes out as &lt;escape&gt;, so it can't inject markup. Frameworks give you the same thing with nicer syntax: {{ $title }} in Laravel's Blade and {{ title }} in Symfony's Twig both escape automatically.

The example writes the template to a temporary file first only because the editor runs a single file. Real applications keep each template in its own file under a templates/ or views/ folder, outside the public web root.

The controller and the router

Now the pieces meet. The controller reads the request, calls the model and renders a view; the router maps a method and a path to a controller method with a regular expression; and a small handle() function plays the front controller:

PHP A complete tiny MVC app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Four simulated requests, four responses: the list, article 2 (with its title safely escaped), a 404 from the controller because article 7 doesn't exist, and a 404 from the router because no route matches /admin. On a real server, public/index.php would call $router->dispatch($_SERVER['REQUEST_METHOD'], ...) once, send http_response_code($response->status) and echo the body.

Look at how cleanly the parts separate: you could replace the array model with the PDO one from the first example without touching the controller, or render JSON instead of HTML by changing only the views. That's the whole point of MVC. Every framework below has these same layers, just with many more features.

Middleware: wrapping every request

Frameworks also let you wrap the whole application in middleware, layers that run before and after every request: start the session, check the login, add security headers, measure timing. Each middleware receives the request and a $next callable that runs the rest of the stack, like an onion:

PHP A middleware pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The guest asking for /admin gets a 302 redirect to /login and never reaches the app, yet still receives the security header, because $securityHeaders wraps everything inside it. Laravel middleware, Symfony event listeners and PSR-15 middleware (Coding Standards and PSRs) all follow this shape.

Laravel

Laravel is the most popular PHP framework. It focuses on developer experience: expressive APIs, sensible defaults and an enormous ecosystem. A taste of its main pieces:

PHP
<?php
// routes/web.php
use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;

Route::get('/articles', [ArticleController::class, 'index']);
Route::get('/articles/{article}', [ArticleController::class, 'show']);

// app/Http/Controllers/ArticleController.php
final class ArticleController
{
    public function show(Article $article)      // route model binding: loads it or returns 404
    {
        return view('articles.show', ['article' => $article]);
    }
}

// Eloquent ORM
$recent = Article::where('published', true)->latest()->limit(10)->get();
HTML
<!-- resources/views/articles/show.blade.php: {{ }} escapes automatically -->
<h1>{{ $article->title }}</h1>
@foreach ($article->comments as $comment)
  <p>{{ $comment->body }}</p>
@endforeach

Laravel includes Eloquent (an active-record ORM), Blade templates, queues, scheduling, mail, notifications, broadcasting and the php artisan console. Official packages add authentication scaffolding, Livewire for interactive pages without writing JavaScript, and admin panels from the community (Filament). It's a great choice for startups, SaaS products and any team that wants to ship quickly.

Symfony

Symfony is both a full-stack framework and a set of more than 50 standalone components that much of the PHP world builds on. Laravel itself uses Symfony's HTTP Foundation, Console, Routing and Mailer components, and Drupal is built on Symfony too. Symfony emphasizes explicit configuration, strict architecture and long-term support releases, which makes it popular for large, long-lived enterprise applications:

PHP
<?php
// src/Controller/ArticleController.php
namespace App\Controller;

use App\Entity\Article;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class ArticleController extends AbstractController
{
    #[Route('/articles/{id}', name: 'article_show', methods: ['GET'])]
    public function show(Article $article): Response
    {
        return $this->render('article/show.html.twig', ['article' => $article]);
    }
}

Symfony uses Twig templates and the Doctrine ORM (a data-mapper ORM, where entities are plain objects and an entity manager saves them). Routes are declared with attributes (Attributes), and the DI container is compiled for speed.

Lighter frameworks and other options

  • Slim and Mezzio: micro-frameworks that give you routing, middleware and PSR-7/PSR-15 support and let you choose everything else. Good for APIs and small services.
  • CodeIgniter: small, fast and easy to learn, with little configuration.
  • CakePHP and Yii: mature full-stack frameworks with strong conventions and code generation.
  • Laminas (formerly Zend Framework): enterprise components, still common in older corporate systems.
  • API Platform (on Symfony): generates REST and GraphQL APIs from your entity classes.

Long-running application servers such as FrankenPHP, RoadRunner and Swoole keep the framework booted in memory between requests instead of starting fresh every time, which can multiply throughput. Laravel supports them through Octane, and Symfony through its Runtime component. The catch is that static state and singletons now leak between requests, one more reason to avoid them.

Content management systems

A CMS is a ready-made application for managing content, with an admin interface, users, media and themes, which you extend instead of building from scratch:

  • WordPress runs more than 40 percent of all websites. It's extended with plugins and themes, which hook into WordPress through actions and filters. WooCommerce turns it into an online shop.
  • Drupal: a more structured CMS (built on Symfony components) used for large, complex sites like universities and governments.
  • Joomla, Craft CMS, Statamic (built on Laravel) and TYPO3: other popular choices.
  • E-commerce platforms: Magento / Adobe Commerce, Shopware, Sylius and PrestaShop.

WordPress's hook system is the observer pattern in its simplest form. A plugin calls add_filter('the_title', $callback), and WordPress passes every post title through all registered callbacks before printing it. Here's the idea in a few lines (a simulation, not WordPress itself):

PHP How WordPress-style hooks work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The title is trimmed (priority 5), uppercased (10) and badged (20): HELLO FROM A PLUGIN [NEW]. WordPress really does store hooks in a global and its functions really do use snake_case names, which is why this example breaks the usual style rules on purpose. It's a design from an older era of PHP, but it's simple to extend, and that's a big part of WordPress's success.

How to choose

You're building A good fit
A blog, marketing site or news site that editors manage WordPress, Craft, Statamic or Drupal
An online shop with standard features WooCommerce, Shopware, Magento, or a hosted platform
A custom web application, SaaS product or startup MVP Laravel or Symfony
A large, long-lived enterprise system with many teams Symfony (or Laravel with strict architecture rules)
A small API or microservice Slim, Mezzio, or Laravel/Symfony in a minimal setup

Whatever you choose, the fundamentals in this course carry over: frameworks still run PHP code, still use PDO underneath, still need you to understand HTTP, escaping, sessions and security. Developers who know the foundations debug framework problems in minutes instead of days.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In MVC, which part should contain the SQL query that loads an article?

    The model owns data access and business rules. Views only present data, and the router only maps requests to controllers.
  2. 2. In the tiny MVC app, why does GET /articles/7 return 404 even though a route matches it?

    The route /articles/{id} matches, so ArticleController::show() runs. The model returns null for id 7, and the controller chooses the 404 response.
  3. 3. In the middleware pipeline, why does the redirected guest still get the X-Content-Type-Options header?

    Middleware runs like layers of an onion. The outer layer calls $next, receives the redirect response from the inner login check, and adds its header before returning.
  4. 4. What is a key difference between Laravel's Eloquent and Symfony's Doctrine?

    Active record: $article->save(). Data mapper: $entityManager->persist($article); $entityManager->flush();. Both are mature ORMs with different trade-offs.
  5. 5. A client needs a news site that non-technical editors update daily. What is usually the best starting point?

    A CMS already provides the admin interface, users, media handling and themes. Custom frameworks make sense when the application itself is the product.

Summary

  • Frameworks bundle tested solutions for routing, controllers, middleware, ORM, templates with auto-escaping, validation, auth, queues, CLI tools and testing.
  • MVC separates the model (data and rules), the view (presentation, always escaped) and the controller (handles one request); a front controller and router dispatch each request.
  • Middleware wraps every request in layers for logins, sessions and headers.
  • Laravel focuses on developer experience (Eloquent, Blade, Artisan, a huge ecosystem); Symfony offers reusable components, Twig, Doctrine and long-term support; Slim, Mezzio and others are lighter.
  • Long-running servers (FrankenPHP, RoadRunner, Swoole) keep apps in memory between requests.
  • CMSs like WordPress and Drupal are ready-made applications extended with plugins and hooks; choose them for content sites, and a framework for custom applications.

Next: Deploying PHP Applications