Best Practices
NixPHP gives you a lot of flexibility and freedom.
Following a few simple best practices can help keep your project clean, scalable, and maintainable.
Keep Controllers Thin
Controllers should focus on handling HTTP-specific logic:
Receiving requests, calling services, and returning responses.
Move heavy business logic into separate service classes.
Example:
// Good: Controller is only responsible for flow control
public function create()
{
$productService = app()->container()->get('productService');
$product = $productService->create($_POST);
return redirect('/products');
}
Use Services for Business Logic
Complex operations (e.g., creating users, processing orders) should be done inside dedicated service classes.
Example:
namespace App\Services;
class ProductService
{
public function create(array $data)
{
// Validation, database operations, etc.
}
}
- Keeps your code modular.
- Makes testing and maintenance easier.
Use Events to Decouple Features
Instead of hardcoding everything, use event()->dispatch()
and event()->listen()
to make your application more flexible and extensible.
Example:
event()->dispatch('user.registered', $user);
- Other parts of your app can react to events without changing the core code.
Handle Errors Cleanly
Always use the abort()
helper when something goes wrong.
Example:
$product = database()->find('products', $id);
if (!$product) {
abort(404, 'Product not found.');
}
- Makes sure that the user sees proper error pages.
- Keeps your controller flow clean and predictable.
Organize Config and Services
- Keep all important configuration in
app/config.php
. - Use the container (
app()->container()
) to manage your services centrally. - Prefer string keys like
'productService'
,'userRepository'
instead of full class names.
Good example:
app()->container()->set('userRepository', function () {
return new \App\Repositories\UserRepository();
});
Write Custom Helpers if Needed
If you find yourself repeating common tasks (like escaping output or creating responses),
feel free to add your own global helpers.
NixPHP encourages building small, reusable tools that fit your needs.
Example:
use function NixPHP\s;
<h1>Hello, <?= s($user->name) ?>!</h1>
Summary
- Thin Controllers → Heavy Services
- Use Events for extension and decoupling
- Handle errors consistently with
abort()
- Manage all services via the container
- Organize config cleanly
- Build small reusable helpers when needed
NixPHP gives you the freedom to structure your app your way —
following these best practices will help you build clean and scalable projects.