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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package origins

languages

Framework Documentation PHP Origins

Index

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:

  1. Clone the Origins repository into your development environment:

  2. Install Composer dependencies:

  3. Configure your web server to route requests to the framework's public directory.

Main Requirements

PHP 8.0

Key Concepts

The Origins framework is built upon a few core concepts:

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.

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:

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

Technical Details

  1. The Thread class uses temporary files to manage thread execution state.
  2. The execution command is automatically adjusted for Windows and Unix environments.
  3. Temporary files are automatically removed after execution.

Benefits

Documentação do Framework PHP Origins

Índice

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:

  1. Clone o repositório do Origins em seu ambiente de desenvolvimento:

  2. Instale as dependências do Composer:

  3. Configure seu servidor web para direcionar as solicitações para o diretório public do framework.

Principais Requisitos

PHP 8.0

Conceitos Principais

O framework Origins é construído com base em alguns conceitos fundamentais:

Uso Básico

Para criar um aplicativo web usando o framework Origins, siga estas etapas:

  1. Defina seus Controllers: Crie classes de Controller e marque-as com o atributo Controller.

  2. Defina os Endpoints: Utilize os atributos Get, Post, Delete e Put para mapear os métodos dos Controllers para os endpoints da API.

  3. Inicie o Framework: Crie uma instância do Origin e chame o método run() 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:

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

Detalhes Técnicos

  1. A classe Thread utiliza arquivos temporários para gerenciar o estado de execução das threads.
  2. O comando de execução é ajustado automaticamente para ambientes Windows e Unix.
  3. Ao finalizar a execução, os arquivos temporários são removidos automaticamente.

Benefícios


All versions of origins with dependencies

PHP Build Version
Package Version
Requires php Version ^8.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package danieltm/origins contains the following files

Loading the files please wait ...