Serapha PHP Framework

website·Indexed 29 days ago

https://seraphalab.github.io

A 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.

Tokens
6.4K
Snippets
32
Records
46
Agent score
74%

What's inside Serapha

  1. Overview of Serapha Framework features

    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.
  2. 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/sanite for CRUD operations and robmorgan/phinx for 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 .env files 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.
  3. 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 Provider class defines two primary lifecycle methods:

    1. register(): Used to bind services into the container.
    2. boot(): Used to initialize configurations or services after all providers have been registered.
  4. 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 as carry0987/template-engine and carry0987/sanite.
  5. Group routes with prefixes and middleware

    Use Route::prefix() and Route::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']);
    });
  6. 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 base Serapha\Model\Model class. The base class provides a $this->db property used to execute database operations via methods like create(), read(), update(), and delete(). 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]);
        }
    }
  7. 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)
  8. Use Models within Serapha Services

    To use a model inside a service, utilize the Serapha\Model\ModelLocator class. The ModelLocator::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);
        }
    }
  9. 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.
  10. Use Dependency Injection in Serapha Controllers

    Serapha supports automatic Dependency Injection (DI) in controller constructors. You can type-hint required dependencies (such as Response) to have them injected automatically. For services not automatically injected, use the ServiceLocator::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);
        }
    }
  11. Organize view files in Serapha

    Views in Serapha handle the presentation layer and are stored in the app/View directory. 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.html
  12. Set global data for templates

    Use the setData method on the Template class 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')
    ]);