Ir para conteúdo
Fórum Script Brasil
  • 0

Projeto semiLaravel -- versão em atualização [28/01/2025 16:40]


Frank K Hosaka

Pergunta

Nessa atualização, eu fiz as modificações para o código rodar tanto no laptop Windows bem como no Hostinger Linux.

 
arquivo .htaccess
RewriteEngine On
# Redirecionar tudo para index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

arquivo teste.php
<?php
class teste {
    static function Inicio() {
        $produtos=tbprod::orderBy('prod','ASC')->select('*')->limit(10)->get();
        $dia=date('Y-m-d');$contad=101;$contac=101;$valor=0;$hist="nenhum";
        $lcto = tbdiario::orderBy('lcto', 'DESC')->select('lcto')->get()[0]->lcto+1;
        $novo=tbdiario::insert(['dia' => $dia,'lcto'=>$lcto,'contad'=>$contad,
            'contac'=>$contac,'valor'=>$valor,'hist'=>$hist]);
        $lcto=15032;
        $produtos=tbhistprod::join('tbprod','tbprod.codprod = tbhistprod.codprod')
            ->join('tbpessoa','tbhistprod.codp=tbpessoa.codp')
            ->select('*',[['lcto','=',$lcto]])->get();
        $somaProdutos=tbhistprod::select(['sum(custototal) as soma'], 
            [['lcto','=',$lcto]])->get()[0]->soma;
        header("location:testeNovoInicio($somaProdutos)"); // o correto é self::NovoInicio($somaProdutos); aqui o teste é no roteador
    }
    
    static function NovoInicio($somaProdutos) {       
        echo "olá mundo, a soma dos produtos deu";
        imprimir($somaProdutos);
    }
}

arquivo index.php
<?php
require('config.php');
$requestUri = $_SERVER['REQUEST_URI'];
$path = substr($requestUri, strlen($basePath));
if ($path == "") {
    // $path = "loginLogin()";
    $path="testeInicio()";
}
if (preg_match('/^([a-z]+)([A-Z][a-zA-Z]*)\((.*)\)$/', $path, $matches)) {
    $classe = $matches[1];
    $metodo = $matches[2];
    $argumentos = explode(',',$matches[3]);
    $argumentos = array_map('urldecode', $argumentos); 
    if (!empty($argumentos[0] && !empty($argumentos))) {
        $classe::$metodo(...$argumentos);
    } else { 
        $classe::$metodo();
    }
} else {
    echo "Formato de URL inválido.";
}

listagem parcial do arquivo config.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set('America/Sao_Paulo');

$baseDir = $_SERVER['SERVER_NAME'] === 'frank.com' ? 
    $_SERVER['DOCUMENT_ROOT'] : $_SERVER['DOCUMENT_ROOT'].'/semiLaravel/';
$basePath = $_SERVER['SERVER_NAME'] === 'frank.com' ?
    '/' : '/semiLaravel/';

defined('HOST') || define('HOST', 'localhost');
defined('DBNAME') || define('DBNAME', $baseDir === $_SERVER['DOCUMENT_ROOT'] ? 'Diario' : 'diario');
defined('USER') || define('USER', $baseDir === $_SERVER['DOCUMENT_ROOT'] ? 'Root' : 'root');
defined('PASSWORD') || define('PASSWORD', $baseDir === $_SERVER['DOCUMENT_ROOT'] ? '12345678' : '');

function imprimir($imprimir) {
    echo "<pre>";
    print_r($imprimir);
    echo "</pre>";
}

spl_autoload_register(function ($class) {
    $path = str_replace('\\', DIRECTORY_SEPARATOR, strtolower($class)) . '.php';
    if (file_exists($path)) {
        require $path;
    } else {
        echo "classe $class não encontrada";
        exit;
    }
});

class bd {

    private static $bindings = [];
    private static $groupBy = '';
    private static $initialized = false;
    private static $joins = '';
    private static $limit = '';
    private static $orderBy = '';
    private static $pdo;
    private static $result = [];

    static function get() {
        return self::$result;
    }

    protected static function getPdo() {
        self::initialize();
        return self::$pdo;
    }

    protected static function getTableName() {
        $reflection = new \ReflectionClass(static::class);
        return strtolower($reflection->getShortName());
    }

    static function groupBy($columns) {
        if (is_array($columns)) {
            $columns = implode(', ', $columns);
        }
        self::$groupBy = "GROUP BY $columns";
        return new static;
    }

    static function initialize() {
        if (!self::$initialized) {
            $dsn = 'mysql:host=' . HOST . ';dbname=' . DBNAME;
            self::$pdo = new PDO($dsn, USER, PASSWORD);
            self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$initialized = true;
        }
    }

    static function insert($data) {
        self::initialize();
        $table = static::getTableName();
        $columns = implode(', ', array_keys($data));
        $placeholders = ':' . implode(', :', array_keys($data));
        $sql = "INSERT INTO $table ($columns) VALUES ($placeholders)";
        $stmt = self::getPdo()->prepare($sql);
        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        $stmt->execute();
        return self::getPdo()->lastInsertId();
    }

    static function join($table, $condition, $type = 'INNER') {
        self::$joins .= " $type JOIN $table ON $condition";
        return new static;
    }

    static function limit($limit) {
        self::$limit = "LIMIT $limit";
        return new static;
    }

    static function orderBy($column, $direction = 'ASC') {
        self::$orderBy = "ORDER BY $column $direction";
        return new static;
    }

    static function select($columns = '*', $conditions = []) {
        self::initialize();
        $table = static::getTableName();
        if (is_array($columns)) {
            $columns = implode(', ', $columns);
        }
        $whereClause = '';
        self::$bindings = [];
        if (!empty($conditions) && !empty($conditions[0])) {
            foreach ($conditions as $condition) {
                $field = $condition[0];
                $operator = $condition[1];
                $value = $condition[2];
                if ($operator == 'BETWEEN' && is_array($value)) {
                    $whereClause .= "$field BETWEEN :{$field}_start AND :{$field}_end AND ";
                    self::$bindings["{$field}_start"] = $value[0];
                    self::$bindings["{$field}_end"] = $value[1];
                } else {
                    $whereClause .= "$field $operator :$field AND ";
                    self::$bindings[$field] = $value;
                }
            }
            $whereClause = 'WHERE ' . rtrim($whereClause, ' AND ');
        }
        $sql = "SELECT $columns FROM $table" . self::$joins . " $whereClause";
        if (self::$groupBy) {
            $sql .= ' ' . self::$groupBy;
            self::$groupBy = '';
        }
        if (self::$orderBy) {
            $sql .= ' ' . self::$orderBy;
            self::$orderBy = '';
        }
        if (self::$limit) {
            $sql .= ' ' . self::$limit;
            self::$limit = '';
        }
        $stmt = self::getPdo()->prepare($sql);
        foreach (self::$bindings as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        $stmt->execute();
        self::$joins = '';
        self::$result = $stmt->fetchAll(PDO::FETCH_OBJ);
        return new static;
    }

    static function update($data, $conditions) {
        self::initialize();
        $table = static::getTableName();
        $setClause = '';
        foreach ($data as $key => $value) {
            $setClause .= "$key = :$key, ";
        }
        $setClause = rtrim($setClause, ', ');
        $whereClause = '';
        self::$bindings = [];
        if (!empty($conditions)) {
            foreach ($conditions as $condition) {
                $field = $condition[0];
                $operator = $condition[1];
                $value = $condition[2];
                if ($operator == 'BETWEEN' && is_array($value)) {
                    $whereClause .= "$field BETWEEN :{$field}_start AND :{$field}_end AND ";
                    self::$bindings["{$field}_start"] = $value[0];
                    self::$bindings["{$field}_end"] = $value[1];
                } else {
                    $whereClause .= "$field $operator :$field AND ";
                    self::$bindings[$field] = $value;
                }
            }
            $whereClause = 'WHERE ' . rtrim($whereClause, ' AND ');
        }
        $sql = "UPDATE $table SET $setClause $whereClause";
        $stmt = self::getPdo()->prepare($sql);
        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        foreach (self::$bindings as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        $stmt->execute();
        return $stmt->rowCount();
    }
}
 
class tbconta extends bd { }
class tbdiario extends bd { }
class tbhistprod extends bd { }
class tbpessoa extends bd { }
class tbprod extends bd { }
class tbusuarios extends bd { }



Editado por Frank K Hosaka
Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,5k
    • Posts
      652,4k
×
×
  • Criar Novo...