Overview
Controllers handle incoming HTTP requests and return responses to the user. In S-PHP, controllers extend the baseController class and have automatic access to the database and environment configuration.
Creating a Controller
Controllers are located in theapp/Controllers directory and extend the Sphp\Core\Controller class.
app/Controllers/HomeController.php
Base Controller Class
TheController class provides two essential properties that are automatically available in all controllers:
Environment configuration loaded from
app/config/config.phpDatabase instance for executing queries
Constructor Behavior
When you instantiate a controller, the constructor automatically:- Loads the environment configuration from
app/config/config.php - Creates a new
Databaseinstance
Sphp/Core/Controller.php
Accessing the Database
You can access the database directly through the$this->db property:
Controller Methods
Controller methods represent different actions or endpoints in your application:app/Controllers/HomeController.php
Using Models in Controllers
Controllers commonly work with models to interact with the database:Rendering Views
Use theView::render() method to display views from your controller:
Best Practices
Keep Controllers Thin
Move business logic to models and services. Controllers should only handle HTTP concerns.
Use Dependency Injection
Initialize models and services in the constructor for cleaner code.
Handle Exceptions
Always wrap potentially failing operations in try-catch blocks.
Return Consistent Responses
Use consistent response formats for APIs (successResponse, errorResponse).
Next Steps
Models
Learn how to work with models and database operations
Views
Discover how to render views and use templates