Ebcore Entity-Based - PHP Framework


Ebcore is a modern and powerful PHP framework inspired by Entity-Based architecture.
It helps you build complex web applications with ease and elegance.



Key Features:
  • πŸ—οΈ Entity-Based Architecture
  • πŸ›£οΈ Modern Routing System
  • 🧩 object-relational mapper (ORM)
  • πŸ”’ Powerful Middleware System
  • ⚑ Advanced Caching
  • 🎯 Event System
  • πŸ“ Logging System
  • πŸ” Security Features
  • βš™οΈ Flexible Configuration

Installation


Create a new project with Ebcore:
1composer create-project ebcore/skeleton my-project
After successful installation you will see this messages :
1Creating a "ebcore/skeleton" project at "./my-project"
2Installing ebcore/skeleton (v1.0.1)
3 - Installing ebcore/skeleton (v1.0.1): Extracting archive
4Created project in S:\wamp64\www\my-project
5Loading composer repositories with package information
6Updating dependencies
7Lock file operations: 1 install, 0 updates, 0 removals
8 - Locking ebcore/framework (v1.0.1)
9Writing lock file
10Installing dependencies from lock file (including require-dev)
11Installing dependencies from lock file (including require-dev)
12Package operations: 1 install, 0 updates, 0 removals
13 - Installing ebcore/framework (v1.0.1): Extracting archive
14Generating optimized autoload files
15And more lines ...

Configuration


Database Connection Configuration

To set up the connection to your database, you need to configure the database.json file located in the config folder. This file contains essential information such as the host, database name, username, and password, which the application uses to establish a connection with your database. Below is an example structure of the configuration file :

1{
2 "db": {
3 "host": "localhost",
4 "database": "ebcore_db",
5 "username": "root",
6 "password": ""
7 }
8}

Fields explained:

  • host: The database server address (usually localhost for local setups)
  • database: The name of your database the application will connect to
  • username: The username for database authentication
  • password: The password for the database user
Make sure to replace these values with your actual database credentials to ensure the application can connect successfully.

Application Information (app.json)

This file contains general information and configuration settings related to the project itself. It is used internally within the application and does not directly affect the core functionality. However, filling in accurate data can help with project management, debugging, and providing contextual information about your application to other developers or documentation tools.

You can include additional details about your project here, such as its name, version, environment mode, timezone, language settings, and the base URL. These values are useful for configuring the application’s behavior and presentation.

Example structure of app.json:

1{
2 "name": "Ebcore Framework Skeleton",
3 "version": "1.0.0",
4 "debug": true,
5 "timezone": "Asia/Tehran",
6 "locale": "fa",
7 "url": "http://localhost"
8}

Fields explained:

  • name: The name of your project or framework.
  • version: The current version of your project.
  • debug: A boolean indicating whether the application runs in debug mode.
  • timezone: The timezone setting for your application.
  • locale: Language/locale setting, for example, 'fa' for Persian.
  • url: The base URL of your application, useful for generating links and redirects.

Feel free to add more custom fields to this JSON file to include other relevant information about your project, such as author details, description, or deployment environment.

Directory Structure


Entity-Base PHP Framework

This project structure follows a modular and organized design centered around core entities, facilitating a clear separation of concerns. The app/ directory contains the main application logic, with subfolders for entitiesβ€”each representing a key data entity like User. Inside each entity folder, there are dedicated sections for Controllers, Events, and Middlewares, which handle specific responsibilities related to that entity, such as processing user requests, managing events like registration, and enforcing permissions.

The config/ folder holds configuration files such as app.json for general project settings, and database.json for database connection details, ensuring easy management of environment-specific parameters. The public/ directory serves static content like stylesheets, scripts, or the main entry point index.php, which handles all incoming HTTP requests.

                    my-project/
                    β”œβ”€β”€ app/
                    β”‚   └── entities/
                    β”‚       └── User/
                    β”‚           β”œβ”€β”€ Controllers/
                    β”‚           β”‚   └── UserController.php
                    β”‚           β”œβ”€β”€ Events/
                    β”‚           β”‚   └── UserRegisterEvent.php
                    β”‚           └── Middlewares/
                    β”‚               └── PermissionMiddleware.php
                    β”œβ”€β”€ config/
                    β”‚   β”œβ”€β”€ app.json
                    β”‚   β”œβ”€β”€ database.json
                    β”‚   └── middleware.json
                    β”œβ”€β”€ public/
                    β”‚   β”œβ”€β”€ .htaccess
                    β”‚   └── index.php
                    β”œβ”€β”€ routes/
                    β”‚   └── web.php
                    └── vendor/
                        └── ebcore/
                            β”œβ”€β”€ Core/
                            β”œβ”€β”€ Middlewares/
                            └── Packages/
                

The routes/ folder contains route definitions, mapping URLs to the corresponding controllers, enabling flexible URL management and request handling. The vendor/ directory is used for third-party libraries installed via Composer, providing reusable components and tools for development.

Overall, this architecture emphasizes modularity, maintainability, and scalability. It groups related functionalities around entities, making it easier to develop, test, and extend the application. The clear separation of configuration, core logic, and static assets aligns with best practices in modern PHP application design, leading to a clean, organized, and efficient project structure.

Starter Kit Overview


This starter kit provides a ready-to-use architecture based on the Entity-Driven structure, designed for rapid development of robust PHP applications. Built with clarity and flexibility in mind, it includes pre-defined components like UserController, event handling, middleware, and customizable responses.

Developers can easily extend this skeleton by adding new entities, defining routes, and customizing event workflows. The included route examples demonstrate how to handle events, middleware, and custom responses, enabling quick prototyping and scalable development.

Whether you're starting a new project or learning best practices for organized PHP coding, this kit offers a solid foundation. It encourages modular design, clean code, and easy integration with third-party packages.

Deployment


Deployment Instructions

To deploy this project:
  • Clone the repository: git clone https://github.com/sajjadbandezadeh/ebcore-skeleton.git
  • Install dependencies: composer install
  • Configure your environment by editing the config files (app.json, database.json)
  • Upload files to your server, ensuring proper permissions
  • Set up your web server to serve the project (Apache/Nginx)
  • Create and migrate your database

Routing Structure


In Ebcore, routes are defined using the $router->map() method, which registers each route with specific parameters. The syntax for each route is:
1$router->map($method, $path, $modelName, $controller, $action, $event = null, $type = null, $middlewares = [])

Parameters:

  • $method: The HTTP request method (e.g., GET, POST, PUT, DELETE)
  • $path: The URL pattern, with support for parameters (e.g., /users/{id})
  • $modelName: The model associated with this route (replaces the concept of "category")
  • $controller: The controller class handling this route (e.g., 'UserController')
  • $action: The method inside the controller to execute (e.g., 'index')
  • $event (optional): The event to trigger after or before executing the route. This is used for event-driven actions.
  • $type (optional): When specifying an $event, this defines whether the event fires before ('before') or after ('after') the controller action.
  • $middlewares (optional): An array of middleware classes that run before (or after) the route executes, used for tasks like permission checks.

Key Points:

  • The $modelName indicates the main data model the route pertains to.
  • When an $event is assigned, $type must be specified as 'before' or 'after', to indicate whether the event triggers before or after the controller action.
  • Multiple middlewares can be added in the $middlewares array, which are executed in order.

Route Examples:

1. Welcome Page

1$router->map('GET', '/', 'System', 'SystemController', 'welcome');
  • Method: GET
  • Path: /
  • Model: System
  • Controller: SystemController
  • Action: welcome
The `SystemController` and `System` action are reserved by Ebcore and cannot be used.

2. List Users

1$router->map('GET', '/users', 'User', 'UserController', 'index');
  • Method: GET
  • Path: /users
  • Model: User
  • Controller: UserController
  • Action: index

3. Run Event After Listing Users

1$router->map('GET', '/users/event', 'User', 'UserController', 'index', 'UserRegisterEvent', 'after');
  • Method: GET
  • Path: /users/event
  • Model: User
  • Controller: UserController
  • Action: index
  • Event: 'UserRegisterEvent'
  • Type: 'after'
This indicates that after executing the index method, the UserRegisterEvent will be triggered.

4. Get User by ID

1$router->map('GET', '/users/{id}', 'User', 'UserController', 'getById');
  • Method: GET
  • Path: /users/{id}
  • ID is a dynamic parameter passed to the controller method.
  • Model: User
  • Controller: UserController
  • Action: getById

5. Custom Response

1$router->map('GET', '/users/customResponse', 'User', 'UserController', 'indexCustomResponse');

6. Custom Data

1$router->map('GET', '/users/customData', 'User', 'UserController', 'indexCustomData');

7. Create User

1$router->map('POST', '/users/create', 'User', 'UserController', 'create');

8. Edit User by ID

1$router->map('PUT', '/users/{id}', 'User', 'UserController', 'edit');

9. Delete User by ID with Middleware

1$router->map('DELETE', '/users/{id}', 'User', 'UserController', 'delete', null, null, ['CheckUserPermissionMiddleware']);
  • Middleware: 'CheckUserPermissionMiddleware' runs before the delete action to verify permissions.

Summary:

  • Routes are explicitly defined with HTTP method, URL pattern, model, controller, and action.
  • Optional parameters like events ($event) and their timing ($type) specify event-driven triggers around controller execution.
  • Middleware can be attached to extend functionality, such as permissions or logging.
  • Dynamic URL parameters (like {id}) are passed directly to controller methods.

Controllers


This section provides an overview of the architecture and responsibilities of the core framework's controller class, which serves as the foundation for custom controllers in the application.

Overview

The base controller class in the framework acts as a mediator between HTTP requests and application logic. It provides essential functionalities such as returning JSON responses, handling request data, and interacting with the database via the DbContext. Custom controllers, like UserController, extend this base class to implement specific features and business logic.

Responsibilities

  • Managing incoming requests and routing to appropriate methods.
  • Returning responses in various formats (JSON, HTML, etc.).
  • Interacting with the database through DbContext.
  • Handling success and error responses consistently.
  • Optional: Triggering events after or before method execution.
  • Protecting routes with middleware.

Typical Workflow

1.Request Handling: When a route matches, the corresponding controller method is invoked.

2.Database Interaction: Controller uses DbContext to perform CRUD operations on entities.

3.Response Formation: Results are returned using the framework's Response class, typically in JSON format.

4.Event & Middleware Handling:

  • If specified, events can be triggered before or after the main action.
  • Middleware can be executed for additional processing, such as permission checks.

Core Methods

Response::json()

Purpose: Sends a JSON response with data.

  • Usage :
1Response::json($data, $message = null, $status = 200, $success = true);
  • Example :
1return Response::json($users);

DbContext

  • Provides access to database entities.
  • Usage :
1$users = DbContext::User()->all();

Event Triggering (Optional)

  • Controlled via route definitions, allowing before/after event handling:
1$router->map('GET', '/users', 'User', 'UserController', 'index', 'UserRegisterEvent', 'after');

Example Controller Structure

1namespace App\entities\User\Controllers;
2 
3use ebcore\framework\DB\DbContext;
4use ebcore\framework\Module\Response;
5 
6class UserController
7{
8 /**
9 * Retrieves all users from the database and returns them as JSON.
10 *
11 * @return \JsonResponse
12 */
13 public function index()
14 {
15 // Fetch all user records
16 $users = DbContext::User()->all();
17
18 // Check if users exist
19 if (empty($users)) {
20 // Send a 404 JSON response if no users found
21 Response::json(null, "No users found", 404, false);
22 }
23 // Send retrieved users as JSON
24 return Response::json($users);
25 }
26}

Summary

  • The framework controller acts as the backbone for implementing business logic.
  • It simplifies response handling and database interactions.
  • Supports event-driven architecture (before/after hooks).
  • Middleware can be attached for permissions, authentication, etc.
  • Ensures consistent response formatting and error handling across the application.

Ebcore ORM Documentation


The Ebcore framework provides a powerful ORM (Object-Relational Mapping) system similar to Laravel's Eloquent, allowing you to interact with your database using expressive PHP syntax. Below is a detailed explanation of the available query methods.

Basic Queries

Fetch All Records

1DbContext::User()->all();
  • Retrieves all records from the users table
  • Equivalent to SELECT * FROM users

Basic Query Construction

1DbContext::User()->newQuery()->get();
  • Creates a new query builder instance for the users table
  • Gets all records without any filters
  • Equivalent to SELECT * FROM users

Conditional Queries (WHERE Clauses)

Equality Check

1DbContext::User()->newQuery()->where("id", "=", "227")->get();
  • Fetches records where id equals 227
  • Equivalent to SELECT * FROM users WHERE id = 227

Greater Than

1DbContext::User()->newQuery()->where("id", ">", "227")->get();
  • Fetches records where id is greater than 227
  • Equivalent to SELECT * FROM users WHERE id > 227

Less Than

1DbContext::User()->newQuery()->where("id", "<", "227")->get();
  • Fetches records where id is less than 227
  • Equivalent to SELECT * FROM users WHERE id < 227

Greater Than or Equal

1DbContext::User()->newQuery()->where("id", ">=", "227")->get();
  • Fetches records where id is greater than or equal to 227
  • Equivalent to SELECT * FROM users WHERE id >= 227

Less Than or Equal

1DbContext::User()->newQuery()->where("id", "<=", "227")->get();
  • Fetches records where id is less than or equal to 227
  • Equivalent to SELECT * FROM users WHERE id <= 227

Not Equal

1DbContext::User()->newQuery()->where("id", "<>", "227")->get();
  • Fetches records where id is not equal to 227
  • Equivalent to SELECT * FROM users WHERE id <> 227

LIKE Operator

1DbContext::User()->newQuery()->where("name", "like", "%test%")->get();
  • Fetches records where name contains "test"
  • The % symbols are wildcards
  • Equivalent to SELECT * FROM users WHERE name LIKE '%test%'

Unsupported Operators

1DbContext::User()->newQuery()->where("id", "BETWEEN", "50 AND 60")->get(); // NOT SUPPORTED
1DbContext::User()->newQuery()->where("id", "IN", "(227,226)")->get(); // NOT SUPPORTED

These operators are currently not supported in Ebcore ORM

Complex Conditions

OR Conditions

1DbContext::User()->newQuery()->orWhere("name", "=", "test1")->orWhere("family", "=", "test")->get();
  • Fetches records where either name equals "test1" OR family equals "test"
  • Equivalent to SELECT * FROM users WHERE name = 'test1' OR family = 'test'

Mixed AND/OR Conditions

1DbContext::User()->newQuery()->orWhere("name", "=", "test1")->Where("family", "=", "test1")->get();
  • Fetches records where (name equals "test1" OR another condition) AND family equals "test1"
  • Equivalent to SELECT * FROM users WHERE (name = 'test1' OR ...) AND family = 'test1'

Multiple AND Conditions

1DbContext::User()->newQuery()->Where("name", "=", "test1")->Where("family", "=", "test1")->get();
  • Fetches records where both name equals "test1" AND family equals "test1"
  • Equivalent to SELECT * FROM users WHERE name = 'test1' AND family = 'test1'

Sorting and Limiting Results

Sorting (ASC)

1DbContext::User()->newQuery()->orderBy('id','ASC')->get();
  • Retrieves all records ordered by id in ascending order
  • Equivalent to SELECT * FROM users ORDER BY id ASC

Sorting (DESC)

1DbContext::User()->newQuery()->orderBy('id','DESC')->get();
  • Retrieves all records ordered by id in descending order
  • Equivalent to SELECT * FROM users ORDER BY id DESC

Limiting Results

1DbContext::User()->newQuery()->fetch(10)->get();
  • Retrieves the last 10 records (default order)
  • Equivalent to SELECT * FROM users LIMIT 10

First 10 Records

1DbContext::User()->newQuery()->orderBy('id','ASC')->fetch(10)->get();
  • Retrieves the first 10 records when ordered by id ascending
  • Equivalent to SELECT * FROM users ORDER BY id ASC LIMIT 10

Last 10 Records

1DbContext::User()->newQuery()->orderBy('id','DESC')->fetch(10)->get();
  • Retrieves the last 10 records when ordered by id descending
  • Equivalent to SELECT * FROM users ORDER BY id DESC LIMIT 10

Complex Query Example

1DbContext::User()->newQuery()->where('name', 'LIKE', '%test%')->where('family', 'LIKE', '%test%')->orWhere('created_at', 'LIKE', '2025-03-17%')->orderBy('id','ASC')->fetch(10)->get();
  • Retrieves 10 records where:
    • name contains "test" AND
    • family contains "test" OR
    • created_at is on March 17, 2025
  • Ordered by id in ascending order
  • Equivalent to:
    SELECT * FROM users
    WHERE (name LIKE '%test%' AND family LIKE '%test%')
    OR created_at LIKE '2025-03-17%'
    ORDER BY id ASC
    LIMIT 10

Finding Specific Records

Find by ID

1DbContext::User()->find(180);
  • Retrieves the record with id equal to 180
  • Equivalent to SELECT * FROM users WHERE id = 180

Ebcore ORM CRUD Operations

Create Operation

1$user = array();
2$user["name"] = $name;
3$user["family"] = $family;
4$user["created_at"] = date("Y/m/d h:i:sa");
5$created_user = DbContext::User()->create($user);
  • Creates a new user record with the provided data
  • Accepts an array of field-value pairs for the new record
  • Automatically sets the creation timestamp
  • Returns the created user object (as associative array) if successful
  • Returns false if creation failed
  • Similar return format to update operation
  • Equivalent to INSERT INTO users (name, family, created_at) VALUES ('$name', '$family', '$formatted_date')

Update Operation

1$user["name"] = $name;
2$updated_user = DbContext::User()->update([$user,$id]);
  • Updates user information for the specified ID
  • Accepts an array of field-value pairs to update
  • Returns the updated user object (as associative array) if successful
  • Returns false if update failed
  • The return value comes from $stmt->fetch(\PDO::FETCH_ASSOC)
  • Equivalent to UPDATE users SET name = '$name' WHERE id = $id

Delete Operation

1DbContext::User()->delete($id); // Return true or False
  • Deletes a user record with the specified ID
  • Returns true if deletion was successful
  • Returns false if deletion failed
  • Equivalent to DELETE FROM users WHERE id = $id

This documentation covers the basic query building capabilities of Ebcore ORM. The fluent interface allows for chaining methods to build complex queries with ease.

Middleware System


Middleware in the framework acts as an intermediary layer between the incoming HTTP request and the application's core logic. It provides mechanisms to process, intercept, and modify requests and responses before reaching controllers or after their execution.

Overview

The primary purpose of middleware includes: authorization and authentication, logging, request modifications, error handling, and security enforcement.

Responsibilities

  • Authorization & Authentication: Verify if the user has the required permissions to access certain routes or resources.
  • Logging & Monitoring: Record details about requests, user activities, or errors.
  • Request/Response Handling: Modify or augment request data or responses before they reach controllers or after responses are generated.
  • Error Handling: Catch and process exceptions or errors that occur during request processing.
  • Security: Enforce security policies such as IP filtering, rate limiting, etc.

Structure and Workflow

A middleware class typically extends a base class BaseMiddleware and overrides the handle() method. Inside handle(), you implement your logicβ€”the check, logging, modification, etc.

  • If the request passes validation, calling parent::next() proceeds to the next middleware or controller.
  • If the request fails the check (e.g., permission denied), you terminate the process and return a response directly, often with an error status.

Example Middleware: Permission Check

1<?php
2 namespace App\entities\User\Middlewares;
3
4 use ebcore\framework\Middlewares\BaseMiddleware;
5 use ebcore\framework\Module\Response;
6 use ebcore\framework\Packages\Logger\Logger;
7 class CheckUserPermissionMiddleware extends BaseMiddleware
8 {
9 private $requiredPermission;
10 /**
11 * Constructor to set the required permission.
12 * @param string $permission - The permission needed to proceed.
13 */
14 public function __construct($permission = 'view')
15 {
16 $this->requiredPermission = $permission;
17 }
18 /**
19 * Handle method to perform permission check and logging.
20 * This method is called for each request passing through this middleware.
21 */
22 public function handle()
23 {
24 // Check if the user has the required permission
25 if (!$this->checkPermission()) {
26 // Log a warning if permission is denied
27 Logger::warning("Permission denied for user", [
28 'permission' => $this->requiredPermission,
29 'user_id' => $_SESSION['user_id'] ?? null
30 ]);
31 // Return a JSON response with 403 Forbidden status
32 return Response::json(null, "You do not have the required permission", 403, false);
33 }
34 // If permission granted, continue to next middleware or controller
35 return parent::next();
36 }
37
38 /**
39 * Method to verify user permissions from the session or context.
40 * @return bool
41 */
42 private function checkPermission()
43 {
44 return isset($_SESSION['user_permissions']) &&
45 in_array($this->requiredPermission, $_SESSION['user_permissions']);
46 }
47 }

Usage Notes

  • Middleware is registered within route definitions, often with optional parameters configured in constructor.
  • The order of middleware execution matters; they are processed sequentially.
  • Middleware can access and modify request data, perform pre- or post-processing, and halt the request by returning a response early.

Summary

Middleware provides an essential layer for request filtering, security, logging, and request/response manipulation. Proper usage ensures modular and maintainable code, and enhances overall application security and observability.

Event System


Overview

Events in the framework facilitate decoupled execution of specific actions at certain points in the application lifecycle. They provide a way to trigger custom logicβ€”such as logging, notifications, data processingβ€”when particular actions occur. This architecture supports scalability, maintainability, and modular design.

Key features include:

  • Execution Control: Ensuring events are not executed multiple times unnecessarily.
  • Error Handling: Managing exceptions during event execution.
  • Flexible Triggering: Events can be invoked synchronously or asynchronously as needed.

Responsibilities

  • Implement Event Logic: Encapsulate specific functionality that occurs in response to system stimuli (e.g., user registration).
  • Control Execution: Prevent duplicate runs, manage retry logic.
  • Manage State: Mark events as executed or reset status as needed.
  • Decouple Code: Allow independent modules to listen and respond to system events without tight coupling.

Structure and Workflow

Extension of Base Event Class:

Events inherit from a core Events class, which provides execution control and other utilities.

Execution Method (execute()):

  • Contains the main functional logic to be run when the event is triggered.
  • Checks if the event has already been executed to prevent reruns.
  • Implements try-catch blocks for exception handling.
  • Marks the event as successfully executed upon completion.

Example Code Breakdown: UserRegisterEvent

1<?php
2
3namespace App\entities\User\Events;
4
5use ebcore\framework\Core\Events;
6use ebcore\framework\DB\DbContext;
7
8class UserRegisterEvent extends Events
9{
10 public function execute(): void
11 {
12 // Check if this event has already been executed
13 if ($this->isExecuted('UserRegisterEvent')) {
14 return; // Exit if already run
15 }
16
17 try {
18 // Prepare user data array
19 $user = array();
20 $user["name"] = "test1"; // User's first name
21 $user["family"] = "test1"; // User's family name
22 $user["created_at"] = date("Y/m/d h:i:sa"); // Current timestamp
23
24 // Save new user to database
25 DbContext::User()->create($user);
26
27 // Mark event as executed to prevent reruns
28 $this->markAsExecuted('UserRegisterEvent');
29 } catch (\Exception $e) {
30 // Reset execution status if error occurs
31 $this->resetExecution('UserRegisterEvent');
32 throw $e; // Re-throw exception for further handling
33 }
34 }
35}

Explanation:

  • Namespace & Class Declaration:

Located within App\entities\User\Events, the class inherits from the core Events class.

  • execute() Method:

Checks if this event has already been executed with $this->isExecuted(). If not executed, attempts to create a new user in the database: Initializes user data array. Uses DbContext::User()->create() to insert data. Marks event as completed with $this->markAsExecuted(). If an error occurs, resets the execution status with $this->resetExecution() to allow retries and rethrows the exception.

Usage and Triggering

Once defined, this event can be triggered programmatically where needed, for example:

1$event = new UserRegisterEvent();
1$event->execute();

Or via event dispatcher mechanisms, depending on the framework's architecture.

Summary

  • The framework's event system allows creating small, self-contained routines that react to application points.
  • They manage execution states, prevent duplicate runs, and handle exceptions gracefully.
  • Events help in maintaining clean, decoupled, and scalable codebase by encapsulating logic that responds to specific system activities.

Cache System


Overview

The Cache system provides an easy-to-use interface for caching data within the framework. It manages temporary storage of key-value pairs in the filesystem, improving performance by reducing repetitive data processing or database access. This class handles cache initialization, storage, retrieval, validation, and cleanup operations.

Namespace and Usage

To utilize the cache functions, import the Cache class:

1use ebcore\framework\Core\Cache;

Core Functions

1. Cache::initialize()

Purpose:

Prepares the cache environment by checking if the designated cache directory exists. If it does not exist, this method creates the directory with permissions set to 0777 to ensure read/write access.

Usage:
1Cache::initialize();
Details:
  • Checks if /storage/cache directory exists.
  • If absent, creates the directory and sets permissions to 0777.

2. Cache::put($key, $value)

Purpose:

Stores a value in the cache associated with a specific key.

Parameters:
  • $key (string): The identifier for the cached data.
  • $value (mixed): The data to cache. Could be string, number, object, etc.
Usage:
1Cache::put("key1", "value");
Functionality:
  • Creates or updates the cache file named after $key.
  • Writes $value into the cache file.

3. Cache::put($key, $value)

Purpose:

Retrieves the cached data for a specified key.

Parameters:
  • $key (string): The identifier for the cached data.
Returns:
  • The cached value associated with $key, or null if the key does not exist.
1$value = Cache::get("key1");
Notes:
  • If the cache for $key does not exist, returns null.

4. Cache::has($key)

Purpose:

Checks whether a cache entry exists for the specified key.

Parameters:
  • $key (string): The key to verify.
Returns:
  • true if the cache exists for $key.
  • false otherwise.
Usage:
1if (Cache::has("key1")) {
2 // cache exists
3}

5. Cache::forget($key)

Purpose:

Deletes the cache entry for the specified key from memory (filesystem).

Parameters:
  • $key (string): The key to delete.
Usage:
1Cache::forget("key1");

6. Cache::cleanup()

Purpose:

Clears the entire cache directory, removing all cached entries.

Usage:
1Cache::cleanup();
Notes:

Useful for bulk clearing cache data to free up space or reset cache state.

7. Cache::decrement($key)

Purpose:

Decreases the numeric value stored in cache for the specified key by one.

Parameters:

$key (string): The key whose value should be decreased.

Usage:
1Cache::decrement("key1");
Prerequisites:
  • The value stored under $key must be numeric.
  • If not numeric, the behavior is undefined (may cause errors or no change).

7. Cache::increment($key)

Purpose:

Increases the numeric value stored under the given key by one.

Parameters:

$key (string): The key to increment.

Usage:
1Cache::increment("key1");
Prerequisites:
  • The value associated with $key must be numeric.

Initialization Strategy

Before performing cache operations, always initialize the cache environment:

1Cache::initialize();

This ensures the cache directory exists and is writable, preventing runtime errors.

Usage Example

1use ebcore\framework\Core\Cache;
2
3// Initialize cache system
4Cache::initialize();
5
6// Store data
7Cache::put("myKey", "Sample Data");
8
9// Retrieve data
10$data = Cache::get("myKey");
11
12// Check existence
13if (Cache::has("myKey")) {
14 // Do something
15}
16
17// Increment/decrement
18Cache::increment("counter");
19Cache::decrement("counter");
20
21// Clear specific cache
22Cache::forget("myKey");
23
24// Clear all cache
25Cache::cleanup();

Summary

This cache system offers a straightforward

Conclusion


In summary, the framework provides a comprehensive set of tools that enable developers to build scalable, efficient, and maintainable applications. From routing requests with controllers and middleware to managing data through models, views, and events, each component plays a vital role in creating a cohesive architecture. The caching system further enhances performance by allowing temporary data storage, reducing database load, and speeding up response times. By utilizing these well-structured modules together, developers can develop robust applications with improved performance, better resource management, and easier maintainability. Mastery of these core components empowers developers to optimize their workflows and deliver high-quality software solutions.

Β© 2025 - Ebcore Framework v1.0.0