PHP code example of danieltm / origins

1. Go to this page and download the library: Download danieltm/origins library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

danieltm / origins example snippets


use Daniel\Origins\Annotations\Dependency;
use Daniel\Origins\Annotations\Profile;

#[Dependency]
#[Profile('dev', 'test')]
class DevelopmentService
{
}

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");
        }
    }
}

use Daniel\Origins\FilterPriority;

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

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



namespace App\Aspects;

use Daniel\Origins\Aop\Aspect;
use ReflectionMethod;

class LoggingAspect extends Aspect
{
    public function pointCut(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs): bool
    {
        return true; // You can put logic here to filter specific methods
    }

    public function aspectBefore(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs)
    {
        error_log("Executing method: " . $method->getName());
    }

    public function aspectAfter(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs, mixed &$result)
    {
        error_log("Method executed: " . $method->getName());
    }
}



namespace App\Aspects;

use Daniel\Origins\Aspect;
use ReflectionMethod;

class LoggingAspect extends Aspect
{
    public function aspectBefore(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs)
    {
        error_log("Executing method: " . $method->getName());
    }
}

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::trace("Entering authentication flow", "app.log");
Log::debug(["userId" => 42], "app.log");
Log::info("User successfully logged in", "app.log");
Log::warning("Unauthorized access attempt", "security.log");
Log::error("Unexpected error processing request", "errors.log");
Log::log("A message with an explicitly selected level", "DEBUG", "app.log");

try {
    processRequest();
} catch (Throwable $exception) {
    Log::error("Request processing failed", "errors.log", $exception);
}

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

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

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



use Daniel\Origins\Controller;
use Daniel\Origins\Get;
use Daniel\Origins\Request;

#[Controller]
class UserController
{

    #[Inject]
    private Service $service;

    #[Get('/users')]
    public function getAllUsers()
    {
        // Logic
    }

    #[Get("/")]
    public function index(Request $req){
        $headers = $req->getHeaders();
        $body = $req->getBody();
    }   

    #[Get("/number")]
    public function getNumber(){
        echo $this->service->getNumber();
    }
}

// true for a single instance, false for per-request
#[Dependency(true)]
class Service{

    public function getNumber() : int{
        return rand();
    }
}



    aniel\Origins\Origin;

    $app = Origin::initialize();
    $app->run();




class MyConfig extends OnInit{
    // Possible to inject dependencies during initialization but only for classes configured to start simultaneously

    #[Override]
    public function ConfigOnInit() : void{
        // Your config
    }
}


namespace Daniel\Origins;

interface Runnable
{
    public function run();
}

namespace Daniel\Origins;

final class ExampleTask implements Runnable
{
    public function run()
    {
        // Logic for the task to run in the background
        echo "Running task in thread...\n";
    }
}

$runnable = new ExampleTask();
$thread = new Thread($runnable);
$thread->start();

// Waits until the task is completed
$thread->waitUntilFinished();

echo "Task completed!\n";

use Daniel\Origins\Annotations\Dependency;
use Daniel\Origins\Annotations\Profile;

#[Dependency]
#[Profile('dev', 'test')]
class ServicoDeDesenvolvimento
{
}

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

        Log::info("$caminho: $metodo", "logs/requests.log");

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

use Daniel\Origins\FilterPriority;

#[FilterPriority(10)]
final class HighPriorityFilter extends Middleware
{
    // Lógica do Middleware
}

#[FilterPriority(1)]
final class LowPriorityFilter extends Middleware
{
    // Lógica do Middleware
}



namespace Daniel\Origins\Aop;

use ReflectionMethod;

abstract class Aspect
{
    public function __construct() {}

    abstract public function pointCut(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs): bool;

    abstract public function aspectBefore(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs);

    abstract public function aspectAfter(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs, mixed &$result);
}



namespace App\Aspects;

use Daniel\Origins\Aop\Aspect;
use ReflectionMethod;

class LoggingAspect extends Aspect
{
    public function pointCut(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs): bool
    {
        return true; // Pode colocar lógica para filtrar métodos específicos
    }

    public function aspectBefore(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs)
    {
        error_log("Executando método: " . $method->getName());
    }

    public function aspectAfter(object &$controllerEntity, ReflectionMethod &$method, array &$varArgs, mixed &$result)
    {
        error_log("Método executado: " . $method->getName());
    }
}

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

        if ($exception instanceof AuthorityAuthorizationException) {
            echo "Você não tem permissão para acessar esta página.";
            exit;
        }

        echo "Erro interno do servidor.";
        exit;
    }
}

Log::trace("Entrando no fluxo de autenticação", "app.log");
Log::debug(["usuarioId" => 42], "app.log");
Log::info("Usuário logado com sucesso", "app.log");
Log::warning("Tentativa de acesso sem permissão", "security.log");
Log::error("Erro inesperado ao processar requisição", "errors.log");
Log::log("Uma mensagem com nível escolhido explicitamente", "DEBUG", "app.log");

try {
    processarRequisicao();
} catch (Throwable $exception) {
    Log::error("Falha ao processar a requisição", "errors.log", $exception);
}

// no controlador
renderPage("index.php", ["number" => rand()]);

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

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



use Daniel\Origins\Controller;
use Daniel\Origins\Get;
use Daniel\Origins\Request;

#[Controller]
class UserController
{

    #[Inject]
    private Servico $servico;

    #[Get('/users')]
    public function getAllUsers()
    {
        
    }

    #[Get("/")]
    public function index(Request $req){
        $headers = $req->getHeaders();
        $body = $req->getBody();
    }   

    #[Get("/number")]
    public function getNumber(){
        echo $this->servico->getNumber();
    }
}

//true se for apenas 1 instacia e false se for por request
#[Dependency(true)]
class Servico{

    public function getNumber() : int{
        return rand();
    }

}



    aniel\Origins\Origin;

    $app = Origin::initialize();
    $app->run();




   class MinhaConfig extends OnInit{
        //possivel injetar dependecia na inicalização porem apenas classes configuradas para inicar no mesmo momento
    
        #[Override]
        public function ConfigOnInit() : void{
            //sua consfig
        }
    }


namespace Daniel\Origins;

interface Runnable
{
    public function run();
}

namespace Daniel\Origins;

final class ExampleTask implements Runnable
{
    public function run()
    {
        // Lógica da tarefa a ser executada em segundo plano
        echo "Executando tarefa em thread...\n";
    }
}

$runnable = new ExampleTask();
$thread = new Thread($runnable);
$thread->start();

// Aguarda até que a tarefa seja concluída
$thread->waitUntilFinished();

echo "Tarefa concluída!\n";