Download the PHP package danieltm/origins without Composer
On this page you can find all versions of the php package danieltm/origins. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package origins
languages
- Português (PT)
- English (EN)
Framework Documentation PHP Origins
Index
- Introduction
- Installation
- Main Requirements
- Key Concepts
- Basic Usage
- Profile-based Activation
- Middleware
- Example
- Middleware Priority
- Initial Configuration
- Aspect-Oriented Programming (AOP)
- Controller Advice
- Example
- Log
- Usage Example
- View Rendering
- Path Variables
- Example
- Controller Code Example
- Customizing Configuration (Optional)
- Threads with the
ThreadClass- Implementing the
RunnableInterface - Using the
ThreadClass - Available Methods in the
ThreadClass - Technical Details
- Benefits
- Implementing the
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
To start using the Origins framework, follow these simple steps:
-
Clone the Origins repository into your development environment:
-
Install Composer dependencies:
- Configure your web server to route requests to the framework's
publicdirectory.
Main Requirements
PHP 8.0
Key Concepts
The Origins framework is built upon a few core concepts:
-
Controller: Classes marked with the
Controllerattribute containing methods corresponding to API endpoints. -
Dependency Injection: Automatically manages class creation and injects necessary dependencies.
-
Routing Attributes: The
Get,Post,Delete, andPutattributes 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
To create a web application using the Origins framework, follow these steps:
-
Define Your Controllers: Create Controller classes and mark them with the
Controllerattribute. -
Define Endpoints: Use the
Get,Post,Delete, andPutattributes to map controller methods to API endpoints. - Initialize the Framework: Create an instance of
Originand call therun()method to start routing and dispatching requests.
Profile-based Activation
Use Profile to register a managed class only for selected application profiles:
Set the active profile in the project's .env file:
Classes without Profile are always active. An annotated class is inactive when app.profile is absent or does not match any value. The rule applies to dependencies, controllers, middlewares, aspects, initializers, controller advice, and scannable classes. Production metadata is automatically rebuilt when the active profile changes.
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
A middleware for logging requests:
Middleware Priority
The FilterPriority attribute can be used to set the execution priority of middlewares. Higher-priority middlewares (numerically larger values) are executed first.
Initial Configuration
Create a .htaccess file in the root of your project to route requests. This serves as the request engine:
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
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
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 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
Managing authentication and permissions:
Log
The integrated logging system allows recording events in files for monitoring or auditing. Use the Log class to record trace, debug, information, warning, or error messages.
Usage Example
An exception can be passed as the last argument to error(). Its class, message,
origin, and stack trace will be written after the log message:
Set the minimum level in the project's .env file:
The available levels are TRACE, DEBUG, INFO, WARNING, ERROR, and OFF.
The default is INFO. A configured level includes messages at that level and all
higher-severity messages; for example, DEBUG records DEBUG, INFO, WARNING,
and ERROR.
View Rendering
The framework allows rendering dynamic pages with data. Use the renderPage method to pass a data model to a view.
Path Variables
Endpoints can contain path variables, like {id}. Use the getPathVar method to retrieve these variables as an associative array.
Example
Controller Code Example
Here is an example of creating a Controller and mapping a method to an endpoint:
Controller Code Example
Here is an example of creating the index:
Customizing Configuration (Optional)
If you need to customize the framework configuration, extend the class:
OnInit.php: This file contains an abstract class defining a method to configure the framework during initialization.
Threads with the Thread Class
The framework now supports running tasks in threads using the Thread class. This functionality is useful for executing long-running tasks in the background without blocking the main application execution.
Implementing the Runnable Interface
To use the Thread class, implement the Runnable interface and define the run method, which will contain the task logic.
Using the Thread Class
The Thread class enables creating and managing threads simply. Here's an example:
Available Methods in the Thread Class
start(): Starts thread execution.isFinished(): bool: Checks if the task is completed.waitUntilFinished(): void: Blocks execution until the task is completed.
Technical Details
- The
Threadclass uses temporary files to manage thread execution state. - The execution command is automatically adjusted for Windows and Unix environments.
- Temporary files are automatically removed after execution.
Benefits
- Allows long-running tasks to execute in the background.
- Prevents blocking the main application execution.
- Easy to integrate with existing code.
Documentação do Framework PHP Origins
Índice
- Introdução
- Instalação
- Principais Requisitos
- Conceitos Principais
- Uso Básico
- Ativação por Profile
- Middleware
- Exemplo
- Prioridade de Middleware
- Configuração Inicial
- Programação Orientada a Aspectos (AOP)
- Controller Advice
- Exemplo
- Log
- Exemplo de Uso
- Renderização de Views
- Path Variables
- Exemplo
- Exemplo de Código Controller
- Personalizando a Configuração (Opcional)
- Threads com Classe
Thread- Implementação da Interface
Runnable - Utilização da Classe
Thread - Métodos Disponíveis na Classe
Thread - Detalhes Técnicos
- Benefícios
- Implementação da Interface
Introdução
Origins é um framework PHP minimalista desenvolvido para simplificar o desenvolvimento de aplicativos da web. Ele fornece uma estrutura flexível e escalável para construir aplicativos da web de forma eficiente.
Instalação
Para começar a usar o framework Origins, siga estas etapas simples:
-
Clone o repositório do Origins em seu ambiente de desenvolvimento:
-
Instale as dependências do Composer:
- Configure seu servidor web para direcionar as solicitações para o diretório
publicdo framework.
Principais Requisitos
PHP 8.0
Conceitos Principais
O framework Origins é construído com base em alguns conceitos fundamentais:
-
Controller: Classes marcadas com o atributo
Controllerque contêm métodos correspondentes a endpoints da API. -
Dependency Injection (Injeção de Dependência): Gerencia automaticamente a criação e injeta dependências necessárias nas classes.
-
Atributos de Roteamento: Os atributos
Get,Post,DeleteePutmapeiam métodos de controllers para os endpoints da API. -
Middleware: Classes que interceptam solicitações antes de alcançarem os controllers, permitindo a implementação de lógicas específicas como autenticação ou logging.
-
Controller Advice: Permite um tratamento centralizado e personalizado de exceções e erros que ocorrem durante a execução das requisições.
-
Programação Orientada a Aspectos (AOP): Usa aspectos para implementar preocupações transversais, como logging e segurança.
-
Log: Sistema integrado para registro de eventos e erros, utilizado para monitoramento e depuração.
- Renderização de Views: Suporte para renderizar páginas com passagem de modelos de dados dinâmicos.
Uso Básico
Para criar um aplicativo web usando o framework Origins, siga estas etapas:
-
Defina seus Controllers: Crie classes de Controller e marque-as com o atributo
Controller. -
Defina os Endpoints: Utilize os atributos
Get,Post,DeleteePutpara mapear os métodos dos Controllers para os endpoints da API. - Inicie o Framework: Crie uma instância do
Origine chame o métodorun()para iniciar o roteamento e despachar as solicitações.
Ativação por Profile
Use Profile para registrar uma classe gerenciada somente nos profiles selecionados:
Defina o profile ativo no arquivo .env do projeto:
Classes sem Profile ficam sempre ativas. Uma classe anotada fica inativa quando app.profile não existe ou não corresponde a nenhum valor. A regra vale para dependências, controllers, middlewares, aspectos, inicializadores, controller advice e classes scannable. O cache de produção é reconstruído automaticamente quando o profile ativo muda.
Middleware
Middlewares permitem a interceptação e manipulação de solicitações antes de alcançarem os controllers. Um exemplo comum de uso é o registro de logs ou validações de segurança.
Para criar um middleware, extenda a classe Middleware e implemente o método onPerrequest. O framework garante que o middleware seja executado antes que os controllers sejam acionados.
Configuração Inicial
para iniciar crie um arquivo .htaccess na raiz do seu projeto, isso será o motor de direcionamento das requisições
Exemplo
Um middleware para registro de logs de solicitações:
Prioridade de Middleware
O atributo FilterPriority pode ser usado para definir a prioridade de execução dos Middlewares. Middlewares com maior prioridade (valor numérico mais altos) serão executados antes.
Programação Orientada a Aspectos (AOP)
A Programação Orientada a Aspectos permite a implementação de preocupações transversais, como logging e segurança, de forma modular e reutilizável.
Nota
A Programação Orientada a Aspectos (AOP) é um recurso avançado do framework, utilizado principalmente para lidar com preocupações transversais, como logging e segurança. Embora a AOP não modifique diretamente os controladores, ela pode alterar o comportamento dos métodos, seus argumentos e até o próprio retorno. Como a AOP manipula referências de memória e não clones, ela pode impactar diretamente o estado dos objetos, o que a torna uma área crítica. Devido a esse impacto potencial, é essencial manuseá-la com cuidado, pois alterações inesperadas no fluxo de execução podem afetar outras partes do sistema que dependem dessas referências.
Para criar um aspecto personalizado, estenda a classe Aspect e implemente o método aspectBefore:
Isso garante que a lógica personalizada seja executada antes da execução dos métodos dos controllers, proporcionando maior modularidade e manutenibilidade.
Controller Advice
A funcionalidade de Controller Advice permite capturar e tratar exceções de forma centralizada, promovendo maior organização do código.
Para usar, extenda a classe ControllerAdvice e sobrescreva o método onError. Você pode implementar tratamentos específicos para diferentes tipos de exceções.
Exemplo
Gerenciamento de autenticação e permissões:
Log
O sistema de logging integrado permite registrar eventos em arquivos para monitoramento ou auditoria. Use a classe Log para registrar mensagens de trace, debug, informação, aviso ou erro.
Exemplo de Uso
Uma exceção pode ser informada como último argumento de error(). A classe,
mensagem, origem e stack trace serão escritos depois da mensagem do log:
Configure o nível mínimo no arquivo .env do projeto:
Os níveis disponíveis são TRACE, DEBUG, INFO, WARNING, ERROR e OFF.
O padrão é INFO. O nível configurado inclui as mensagens daquele nível e as de
maior severidade; por exemplo, DEBUG registra DEBUG, INFO, WARNING e
ERROR.
Renderização de Views
O framework permite renderizar páginas dinâmicas com dados. Use o método renderPage para passar um modelo de dados a uma view.
Path Variables
Os endpoints podem conter variáveis de path, como {id}. Use o método getPathVar para obter os valores dessas variáveis como um array associativo.
Exemplo
Exemplo de Código Controller
Aqui está um exemplo de como criar um Controller e mapear um método para um endpoint:
Exemplo de Código Controller
Aqui está um exemplo de como criar o index:
Personalizando a Configuração (Opcional)
Se você precisar personalizar a configuração do framework, pode extender a classe:
OnInit.php: Este arquivo contem uma classe abstrata que define um método para configurar o framework durante a inicialização.
Threads com Classe Thread
O framework agora oferece suporte à execução de tarefas em threads utilizando a classe Thread. Essa funcionalidade é útil para executar tarefas demoradas em segundo plano sem bloquear a execução principal do aplicativo.
Implementação da Interface Runnable
Para utilizar a classe Thread, você deve implementar a interface Runnable e definir o método run, que conterá a lógica da tarefa.
Utilização da Classe Thread
A classe Thread permite criar e gerenciar threads de forma simples. Veja um exemplo de uso:
Métodos Disponíveis na Classe Thread
start(): Inicia a execução da thread.isFinished(): bool: Verifica se a tarefa foi concluída.waitUntilFinished(): void: Bloqueia a execução até que a tarefa seja concluída.
Detalhes Técnicos
- A classe
Threadutiliza arquivos temporários para gerenciar o estado de execução das threads. - O comando de execução é ajustado automaticamente para ambientes Windows e Unix.
- Ao finalizar a execução, os arquivos temporários são removidos automaticamente.
Benefícios
- Permite executar tarefas demoradas em segundo plano.
- Evita bloqueios na execução principal do aplicativo.
- Simples de integrar ao código existente.