Several packages that can help improve your development experience with PHP MVC

When building a custom PHP MVC (Model-View-Controller) framework, there are several important aspects you need to consider: routing, templating, dependency management, database interaction, input validation, and more.

Fortunately, the PHP ecosystem offers a variety of packages to streamline these tasks, improve your code quality, and save you time on common tasks.

In this post, we’ll take a look at several packages that can significantly enhance your development experience while building your own PHP MVC framework.

1. Dependency Injection (DI) with PHP-DI

Dependency Injection is an important concept in modern PHP development. It promotes loose coupling between components and makes your code more testable and maintainable. A Dependency Injection container can automatically handle the creation and injection of dependencies into your classes, making it easier to manage class dependencies.

PHP-DI

Check this git repo and observe that how idea becomes complex when we are not using DI packages.

And this is the git repo which uses DI package and see how easy the code is for developer without worrying about dependent objects to create. DI package auto create dependent objects first.

PHP-DI is one of the most popular Dependency Injection containers for PHP. It simplifies the process of managing your application’s dependencies.

Installation:

composer require php-di/php-di

Example:

use DI\ContainerBuilder;

$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([
    'SomeService' => function() {
        return new SomeService();
    }
]);
$container = $containerBuilder->build();

$someService = $container->get('SomeService');

With PHP-DI, you can inject dependencies into your controllers, services, or other components, which makes your application more modular and testable.


2. Routing with FastRoute

Routing is a fundamental part of any web application. FastRoute is an excellent routing package for PHP, known for its speed and simplicity. It allows you to define routes and map them to controllers and methods with minimal overhead. FastRoute is an optimal choice for lightweight applications.

FastRoute

FastRoute is a fast and efficient routing library designed for handling HTTP requests. It uses a trie-based algorithm to match routes and is optimized for performance.

Installation:

composer require nikic/fast-route

Example:

use FastRoute\RouteCollector;

$dispatcher = FastRoute\simpleDispatcher(function(RouteCollector $r) {
    $r->addRoute('GET', '/', 'HomeController@index');
    $r->addRoute('GET', '/about', 'AboutController@show');
});

// Dispatch the route
$routeInfo = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);

FastRoute allows you to define simple routes and use them efficiently, making it an excellent choice for routing in your custom MVC framework.

Check this Git repo.


3. Templating with Twig

Separation of concerns is one of the key principles of the MVC architecture. Instead of mixing PHP logic with HTML, using a templating engine like Twig ensures that your views are cleaner and more maintainable.

Twig

Twig is a modern templating engine for PHP. It is powerful, fast, and easy to use, allowing you to create templates with minimal code while keeping your application secure by escaping output automatically.

Installation:

composer require "twig/twig:^3.0"

Example:

$loader = new \Twig\Loader\FilesystemLoader('path_to_templates');
$twig = new \Twig\Environment($loader);

echo $twig->render('index.twig', ['name' => 'World']);

Twig allows you to separate HTML from logic, which makes your views more modular and easier to maintain.

Check this Git repo.


4. Database Abstraction with Eloquent ORM

Interacting with a database is a core part of almost every web application. For ease of use and to abstract away the raw SQL queries, an Object-Relational Mapper (ORM) can be a great addition to your framework.

Eloquent ORM

Eloquent ORM is a simple, beautiful, and powerful ORM used by the Laravel framework. It allows you to interact with your database using PHP objects and relationships instead of writing complex SQL queries.

Installation:

composer require illuminate/database

Example:

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([
    'driver' => 'mysql',
    'host' => 'localhost',
    'database' => 'your_database',
    'username' => 'root',
    'password' => '',
]);

$capsule->setAsGlobal();
$capsule->bootEloquent();

$user = User::find(1);
echo $user->name;

With Eloquent, you can easily manage relationships, query data, and perform CRUD operations without having to write raw SQL.

Check this git repo to see how Eloquent works at very basic level.


5. Input Validation with Respect/Validation

Input validation is essential for ensuring the integrity of the data being processed in your application. The Respect/Validation library simplifies this process by providing easy-to-use validators for common types of input.

Respect/Validation

Respect/Validation is a flexible and powerful validation library that allows you to validate user input using simple rules.

Installation:

composer require respect/validation

Example:

use Respect\Validation\Validator as v;

$email = 'user@example.com';
if (v::email()->validate($email)) {
    echo 'Valid email';
} else {
    echo 'Invalid email';
}

Respect/Validation makes input validation easy, helping you ensure that user inputs meet your required criteria before processing them.


6. Logging with Monolog

Effective logging is vital for debugging and monitoring your application. Monolog is a flexible and powerful logging library that allows you to send logs to a variety of output channels, including files, email, Slack, and more.

Monolog

Monolog is the most widely-used logging library for PHP. It provides support for a variety of logging backends and allows you to easily log events, errors, and warnings in your application.

Installation:

composer require monolog/monolog

Example:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('my_app');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

$log->warning('This is a warning!');
$log->error('This is an error!');

With Monolog, you can keep track of important events and easily debug issues in your application.


7. Session Management with Symfony HttpFoundation

Managing user sessions correctly is important for any web application. The Symfony HttpFoundation component provides robust support for managing sessions, cookies, requests, and responses.

Symfony HttpFoundation

Symfony HttpFoundation is part of the Symfony framework but can be used independently to handle requests, responses, and sessions.

Installation:

composer require symfony/http-foundation

Example:

use Symfony\Component\HttpFoundation\Session\Session;

$session = new Session();
$session->start();
$session->set('user', 'John Doe');
echo $session->get('user'); // Outputs: John Doe

Symfony HttpFoundation simplifies session management and makes it easier to work with HTTP requests and responses.


8. CSRF Protection with Anti-CSRF

Cross-Site Request Forgery (CSRF) is a security vulnerability that can allow malicious users to perform unauthorized actions on behalf of authenticated users. Protecting your forms from CSRF attacks is critical, and Anti-CSRF is a simple library that helps with this.

Anti-CSRF

Anti-CSRF is a lightweight PHP library for preventing CSRF attacks by generating and validating CSRF tokens for your forms.

Installation:

composer require paragonie/anti-csrf

Example:

use ParagonIE\AntiCSRF\AntiCSRF;

$csrf = new AntiCSRF();

// Generate token
$token = $csrf->generateToken();

// Validate token
if ($csrf->validateToken($token)) {
    echo "CSRF Token Valid!";
} else {
    echo "Invalid CSRF Token!";
}

By integrating Anti-CSRF, you can protect your forms and prevent CSRF attacks.


Conclusion

Building a custom PHP MVC framework can be a rewarding learning experience, but it’s also a lot of work. By integrating some of these packages into your project, you can save time, follow best practices, and ensure that your application is robust, secure, and maintainable.

Here’s a recap of the packages we’ve covered:

  1. PHP-DI for Dependency Injection
  2. FastRoute for Routing
  3. Twig for Templating
  4. Eloquent ORM for Database Abstraction
  5. Respect/Validation for Input Validation
  6. Monolog for Logging
  7. Symfony HttpFoundation for Session Management
  8. Anti-CSRF for CSRF Protection

As you progress with your PHP MVC framework, these packages will help you build cleaner, more modular, and scalable applications. Happy coding!