PHP Frameworks: hidden errors to avoid
Frameworks such as Symfony (7.2 at the time of writing) or Laravel are highly customizable and encourage good practices, regardless of your experience and skills.
However, you may still introduce design, security, or performance issues.
Symfony: don't call the $container directly
❌ This one is a classic but still heavily used by developers:
class LuckyController extends AbstractController { public function index() { $myDependency = $this->container->get(MyDependencyInterface::class); // }
It's possible because the parent AbstractController defines $container as protected:
protected ContainerInterface $container;
Source: Symfony - GitHub
While it does work, it's a bad practice for various reasons:
- it harms readability
- it's harder to test
- it relies on global states ($container)
- it could lead to incompatibility issues in the future, as Symfony evolves
✅ Use dependency injection in the constructor instead:
class LuckyController extends AbstractController { public function __construct(private MyDependencyInterface $myDependency) {}
Eloquent ORM: don't use raw queries blindly
Eloquent allows writing SQL queries quite conveniently.
Instead of writing SQL queries directly, developers can use PHP wrappers to interact with database entities.
It also uses SQL bindings behind the scene, so you get injection protection for free, even with untrusted inputs:
User::where('email', $request->input('email'))->get();
❌ However, when you use helpers like whereRaw, you may introduce vulnerabilities:
User::whereRaw('email = "'. $request->input('email'). '"')->get();
✅ At least, always use SQL bindings:
User::whereRaw('email = :email', ['email' => $request->input('email')])->get();
N.B.: the above example does not make sense, but it keeps things simple. In real-world use cases, you may need whereRaw for optimization purposes or to implement very specific where conditions.
Laravel: what about CSRF?
With CSRF attacks, hackers force the end users to execute unwanted actions on an app in which they're currently authenticated.
Laravel has a built-in mechanism to guard against such scenario.
Roughly speaking, it adds a token (hidden field) to be sent along with your requests, so you can verify that "the authenticated user is the person actually making the requests to the application."
Fair enough.
❌ However, some apps skip this implementation.
✅ Whether you should use the built-in middleware is not relevant here, but ensure your app is secured against CSRF attacks.
You may read this page for more details about the implementation in Laravel.
Please secure AJAX requests too.
Eloquent ORM: queries are not optimized "automagically"
Eloquent allows eager/lazy loading, and supports various optimizations, such as query caching, indexing, or batch processing.
However, it does not prevent all performance issues, especially on large datasets.
❌ It's not uncommon to see such loops:
class LuckyController extends AbstractController { public function index() { $myDependency = $this->container->get(MyDependencyInterface::class); // }
But it can lead to memory issues.
✅ When possible, a better approach would leverage Laravel collections and helpers like chunk:
protected ContainerInterface $container;
Check the documentation for more details.
N.B.: It works, but don't forget those helpers are only meant to ease the implementation, so you have to monitor slow queries and other bottlenecks.
Symfony: SRP services
As the documentation says:
useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!
In other words, you will write custom services to handle specific responsibilities for your application.
❌ The documentation is right. It aims to promote a strong architecture, but it's not uncommon to read services that break the Single Responsibility Principle (SRP):
class LuckyController extends AbstractController { public function __construct(private MyDependencyInterface $myDependency) {}
✅ You must respect that principle. It will be easier to test and maintain.
Symfony: public vs. private services
❌ With Symfony, you can use $container->get('service_id') to call any public service.
We saw earlier that calling the $container like that is considered as a bad practice.
You may not resist the temptation to make all services public, so you can retrieve them by their ID almost everywhere in the project.
Don't do that.
✅ Instead, keep most custom services private and use dependency injection.
Wrap up
Hopefully, you will avoid what I like to call "latent errors" or "hidden errors" with frameworks.
If you don't know how to implement it, trust the framework, but be aware some mechanisms may not be enabled by default.
The above is the detailed content of PHP Frameworks: hidden errors to avoid. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
