Serapha PHP Framework
website·Indexed 29 days ago
https://seraphalab.github.ioA lightweight, modular PHP framework designed for modern web development using PHP 8 features. Serapha provides a structured architecture including Controllers, Models, Views, Middleware, and a Service/Provider system to handle business logic and HTTP requests.
What's inside Serapha
- Serapha is a lightweight, modular PHP framework built using PHP 8 features. It provides a set of core utilities including a template engine, i18n support, RESTful API integration, and advanced ORM capabilities. It uses Composer for dependency management.
Overview of Serapha PHP Framework features
Serapha is a lightweight, modular PHP framework designed for modern web development with a focus on simplicity and performance. Its core capabilities include:
- Modular Architecture: Code organization into manageable modules.
- Templating: Built-in template engine for flexible rendering.
- Database Management: Uses
carry0987/sanitefor CRUD operations androbmorgan/phinxfor schema migrations. - Routing & Middleware: Advanced routing system to map URLs to controllers and support for custom middleware to secure or extend applications.
- Dependency Management: Built-in Dependency Injection (DI) container.
- Configuration: Support for
.envfiles to manage different environments. - Business Logic: A dedicated Service Layer for reusable business logic.
- Caching: Built-in Redis integration for caching and other Redis-based features.
Understand the Serapha Provider lifecycle
In Serapha, Providers are used to register and manage shared services (such as database connections, caching systems, and configuration managers) that can be injected into Controllers and Services. The base
Providerclass defines two primary lifecycle methods:register(): Used to bind services into the container.boot(): Used to initialize configurations or services after all providers have been registered.
Serapha Framework Overview
Serapha is a lightweight, modular PHP framework designed for simplicity and performance in web application development. It utilizes modern PHP practices and integrates libraries such ascarry0987/template-engineandcarry0987/sanite.Group routes with prefixes and middleware
UseRoute::prefix()andRoute::group()to organize related routes. This allows you to apply a common URL prefix and shared middleware to all routes defined within the group closure.Route::prefix('admin')->middleware(AuthMiddleware::class)->group(function () { Route::get('/dashboard', [UserController::class, 'dashboard']); Route::get('/profile', [UserController::class, 'profile']); Route::get('/settings', [UserController::class, 'settings']); });Create a data model in Serapha
Models in Serapha handle the data layer by encapsulating CRUD (Create, Read, Update, Delete) logic. To create a model, extend the baseSerapha\Model\Modelclass. The base class provides a$this->dbproperty used to execute database operations via methods likecreate(),read(),update(), anddelete(). These methods typically require a SQL query, a string of bind types (e.g., 'ssisiii'), and the data array.namespace App use Serapha\Model\Model; class UserModel extends Model { public function createUser(array $data) { $query = 'INSERT INTO user (username, password, group_id, language, online_status, last_login, join_date) VALUES (?,?,?,?,?,?,?)'; $bindTypes = 'ssisiii'; $user_data = [ 'username' => $data['username'], 'password' => $data['password'], 'group_id' => $data['group_id'], 'language' => $data['language'], 'online_status' => $data['online_status'], 'last_login' => $data['last_login'], 'join_date' => $data['join_date'] ]; return $this->db->create($query, $bindTypes, $user_data); } public function getUserById(int $id) { $query = 'SELECT * FROM user WHERE uid = ?'; $bindTypes = 'i'; return $this->db->read($query, $bindTypes, ['uid' => $id]); } public function updateUser(array $data, int $id) { $query = 'UPDATE user SET username = ?, password = ?, group_id = ?, language = ?, online_status = ?, last_login = ?, join_date = ? WHERE uid = ?'; $bindTypes = 'ssisiiii'; $user_data = [ $data['username'], $data['password'], $data['group_id'], $data['language'], $data['online_status'], $data['last_login'], $data['join_date'], $id ]; return $this->db->update($query, $bindTypes, $user_data); } public function deleteUser(int $id) { $query = 'DELETE FROM user WHERE uid = ?'; $bindTypes = 'i'; return $this->db->delete($query, $bindTypes, ['uid' => $id]); } }System Requirements for Serapha
To install and run the Serapha framework, the following system requirements must be met:
- PHP 8.1 or higher
- Composer
- A supported web server (Apache, Nginx, or the built-in PHP server)
- Node.js and pnpm (Optional: required only for building front-end assets)
Use Models within Serapha Services
To use a model inside a service, utilize theSerapha\Model\ModelLocatorclass. TheModelLocator::get()method allows you to retrieve an instance of a specific model class to perform data operations within your business logic.namespace App\Service; use Serapha\Service\Service; use Serapha\Model\ModelLocator; use App\Model\UserModel; class UserService extends Service { private UserModel $userModel; public function __construct() { // Use the Model Locator to get an instance of UserModel $this->userModel = ModelLocator::get(UserModel::class); } public function registerUser(array $data) { $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT); return $this->userModel->createUser($data); } public function getUserProfile(int $id) { return $this->userModel->getUserById($id); } }Manage database schema migrations using Phinx
Serapha utilizes Phinx to handle database schema migrations. This allows for versioned migrations to ensure database consistency across different environments.Use Dependency Injection in Serapha Controllers
Serapha supports automatic Dependency Injection (DI) in controller constructors. You can type-hint required dependencies (such asResponse) to have them injected automatically. For services not automatically injected, use theServiceLocator::get()method to retrieve the required service class.namespace App\Controller; use Serapha\Service\ServiceLocator; use Serapha\Routing\Response; use App\Service\UserService; class UserController extends BaseController { private Response $response; private UserService $userService; public function __construct(Response $response) { // Response is injected automatically via DI $this->response = $response; // Services can be retrieved via ServiceLocator $this->userService = ServiceLocator::get(UserService::class); } public function show(string|int $id) { $user = $this->userService->getUserProfile((int) $id); $data = ['user' => $user]; $this->template->render(['header_common.html', 'view_user.html', 'footer_common.html'], $data); } }Organize view files in Serapha
Views in Serapha handle the presentation layer and are stored in theapp/Viewdirectory. View files are typically HTML files containing embedded PHP variables (e.g.,{$variable_name}).app/View ├── footer_common.html ├── header_common.html ├── view_index.html └── view_user.htmlSet global data for templates
Use thesetDatamethod on theTemplateclass to inject global data (such as configuration settings) that should be available across all rendered views.// Example: Setting global config data in BaseController $this->template->setData([ 'config' => $this->config->getConfig('web_config') ]);