PHPackages                             danieltm/origins - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. danieltm/origins

ActiveLibrary

danieltm/origins
================

V2.0.5(1mo ago)32333MITPHPPHP ^8.0

Since Jun 27Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/DanielTM999/origins)[ Packagist](https://packagist.org/packages/danieltm/origins)[ RSS](/packages/danieltm-origins/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)DependenciesVersions (27)Used By (3)

languages
=========

[](#languages)

- [Português (PT)](#documenta%C3%A7%C3%A3o-do-framework-php-origins)
- [English (EN)](#framework-documentation-php-origins)

Framework Documentation PHP Origins
===================================

[](#framework-documentation-php-origins)

Index
-----

[](#index)

- [Introduction](#introduction)
- [Installation](#installation)
- [Main Requirements](#main-requirements)
- [Key Concepts](#key-concepts)
- [Basic Usage](#basic-usage)
- [Middleware](#middleware)
    - [Example](#example)
    - [Middleware Priority](#middleware-priority)
- [Initial Configuration](#initial-configuration)
- [Aspect-Oriented Programming (AOP)](#aspect-oriented-programming-aop)
- [Controller Advice](#controller-advice)
    - [Example](#example-1)
- [Log](#log)
    - [Usage Example](#usage-example)
- [View Rendering](#view-rendering)
- [Path Variables](#path-variables)
    - [Example](#example-2)
- [Controller Code Example](#controller-code-example)
- [Customizing Configuration (Optional)](#customizing-configuration-optional)
- [Threads with the `Thread` Class](#threads-with-the-thread-class)
    - [Implementing the `Runnable` Interface](#implementing-the-runnable-interface)
    - [Using the `Thread` Class](#using-the-thread-class)
    - [Available Methods in the `Thread` Class](#available-methods-in-the-thread-class)
    - [Technical Details](#technical-details)
    - [Benefits](#benefits)

Introduction
------------

[](#introduction)

Origins is a minimalist PHP framework designed to simplify web application development. It provides a flexible and scalable structure for efficiently building web applications.

Installation
------------

[](#installation)

To start using the Origins framework, follow these simple steps:

1. Clone the Origins repository into your development environment:

    ```
    git clone https://github.com/DanielTM999/origins.git
    ```
2. Install Composer dependencies:

    ```
    composer require danieltm/origins
    ```
3. Configure your web server to route requests to the framework's `public` directory.

Main Requirements
-----------------

[](#main-requirements)

PHP 8.0

Key Concepts
------------

[](#key-concepts)

The Origins framework is built upon a few core concepts:

- **Controller**: Classes marked with the `Controller` attribute containing methods corresponding to API endpoints.
- **Dependency Injection**: Automatically manages class creation and injects necessary dependencies.
- **Routing Attributes**: The `Get`, `Post`, `Delete`, and `Put` attributes map controller methods to API endpoints.
- **Middleware**: Classes that intercept requests before they reach controllers, enabling logic implementation like authentication or logging.
- **Controller Advice**: Enables centralized and customized error handling for exceptions during request execution.
- **Aspect-Oriented Programming (AOP)**: Uses aspects to implement cross-cutting concerns such as logging and security.
- **Log**: An integrated system for logging events and errors, used for monitoring and debugging.
- **View Rendering**: Supports rendering pages with dynamic data models.

Basic Usage
-----------

[](#basic-usage)

To create a web application using the Origins framework, follow these steps:

1. **Define Your Controllers**: Create Controller classes and mark them with the `Controller` attribute.
2. **Define Endpoints**: Use the `Get`, `Post`, `Delete`, and `Put` attributes to map controller methods to API endpoints.
3. **Initialize the Framework**: Create an instance of `Origin` and call the `run()` method to start routing and dispatching requests.

Middleware
----------

[](#middleware)

Middlewares allow request interception and manipulation before they reach controllers. A common use case is logging or security validations.

To create a middleware, extend the `Middleware` class and implement the `onPerrequest` method. The framework ensures that middleware is executed before controllers are triggered.

### Example

[](#example)

A middleware for logging requests:

```
final class IpFilter extends Middleware
{
    #[Override]
    public function onPerrequest(Request $req): void
    {
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $method = $_SERVER['REQUEST_METHOD'];

        Log::info("$path: $method", "logs/requests.log");

        if ($method === "POST") {
            $body = json_encode($req->getBody());
            Log::info("$path ==> body: $body", "logs/requests.log");
        }
    }
}
```

### Middleware Priority

[](#middleware-priority)

The `FilterPriority` attribute can be used to set the execution priority of middlewares. Higher-priority middlewares (numerically larger values) are executed first.

```
use Daniel\Origins\FilterPriority;

#[FilterPriority(10)]
final class HighPriorityFilter extends Middleware
{
    // Middleware Logic
}

#[FilterPriority(1)]
final class LowPriorityFilter extends Middleware
{
    // Middleware Logic
}
```

Initial Configuration
---------------------

[](#initial-configuration)

Create a `.htaccess` file in the root of your project to route requests. This serves as the request engine:

```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]

```

Aspect-Oriented Programming (AOP)
---------------------------------

[](#aspect-oriented-programming-aop)

Aspect-Oriented Programming allows the implementation of cross-cutting concerns such as logging and security in a modular and reusable way.

### Note

[](#note)

**Aspect-Oriented Programming (AOP)** is an advanced framework feature primarily used to handle cross-cutting concerns, such as logging and security. **While AOP does not directly modify controllers**, it can alter the behavior of methods, their arguments, and even their return values. Since AOP manipulates memory references rather than clones, it can directly impact the state of objects, making it a critical area. Due to this potential impact, it is essential to handle it carefully, as unexpected changes in the execution flow can affect other parts of the system that rely on these references.

### Aspect Class

[](#aspect-class)

The `Aspect` class provides a way to execute logic before a controller method is executed. This can be used for cross-cutting concerns like logging, security, and data transformation.

```

```

To create a custom aspect, extend the `Aspect` class and implement the `aspectBefore` method:

```

```

This ensures that custom logic runs before the execution of controller methods, allowing for greater modularity and maintainability.

Controller Advice
-----------------

[](#controller-advice)

Controller Advice enables centralized and organized exception handling.

To use, extend the `ControllerAdvice` class and override the `onError` method. Implement specific handling for different exception types.

### Example

[](#example-1)

Managing authentication and permissions:

```
class AuthExceptionHandler extends ControllerAdvice
{
    #[Override]
    public function onError(Throwable $exception): void
    {
        if ($exception instanceof AuthorizationException) {
            header("Location: /login");
            exit;
        }

        if ($exception instanceof AuthorityAuthorizationException) {
            echo "You do not have permission to access this page.";
            exit;
        }

        echo "Internal server error.";
        exit;
    }
}
```

Log
---

[](#log)

The integrated logging system allows recording events in files for monitoring or auditing. Use the `Log` class to record information, warnings, or errors.

### Usage Example

[](#usage-example)

```
Log::info("User successfully logged in", "app.log");
Log::warning("Unauthorized access attempt", "security.log");
Log::error("Unexpected error processing request", "errors.log");
```

View Rendering
--------------

[](#view-rendering)

The framework allows rendering dynamic pages with data. Use the `renderPage` method to pass a data model to a view.

```
// in the controller
renderPage("index.php", ["number" => rand()]);

// in index.php
global $model;
echo $model["number"];
```

Path Variables
--------------

[](#path-variables)

Endpoints can contain path variables, like `{id}`. Use the `getPathVar` method to retrieve these variables as an associative array.

### Example

[](#example-2)

```
$variables = $this->getPathVar();
$id = $variables['id'] ?? null;
```

Controller Code Example
-----------------------

[](#controller-code-example)

Here is an example of creating a Controller and mapping a method to an endpoint:

```
