### Project File Structure Example Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This is a representation of the recommended file and directory structure for the Vibe Cloudioo project. It illustrates the placement of configuration files, core libraries, and modular sections like 'drivers' with examples for 'layout', 'home', and 'users'. ```text / |-- config.php |-- index.php |-- libs_devops.php |-- libs_helper.php | |-- drivers/ | |-- layout/ # Layout principal, estilos y scripts base | | |-- layout.html | | |-- layout.css | | `-- layout.js | |-- home/ | | |-- home.php | | `-- home.html | `-- users/ # Ejemplo de sección "users" | |-- profile/ # Ejemplo de subsección "profile" | | |-- profile.php | | |-- profile.html | | |-- profile.css | | `-- profile.js | |-- users.php | |-- users.html | |-- users.css | `-- users.js | ``` -------------------------------- ### Example SQL Query for a Specific Project Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text An example of a correctly formatted SQL query for the 'my_docs' project, demonstrating the use of the database prefix ('my_docs.') before the table name ('users') and the inclusion of a LIMIT clause. ```sql SELECT * FROM my_docs.users LIMIT 10; ``` -------------------------------- ### SQL Examples: Listing, Counting, and Joining Tables Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Provides practical SQL query examples for common database operations. These include selecting records, counting rows, and performing joins between tables, all while adhering to the required database prefix convention. ```sql -- Listar registros SELECT * FROM my_project.users LIMIT 10; -- Contar registros SELECT COUNT(*) FROM my_project.users; -- Join entre tablas SELECT u.*, p.* FROM my_project.users u INNER JOIN my_project.profiles p ON u.id = p.user_id LIMIT 20; ``` -------------------------------- ### Full Example: Performing Action and Redirecting in JavaScript Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This example demonstrates a complete workflow within a button's onclick event. It updates button text with translations, dynamically adds a CSS file using `publiclink()`, and redirects the user after a delay using `applink()`. ```javascript ``` -------------------------------- ### PHP Configuration File Example Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Defines the structure for the central `config.php` file, which must reside in the project root. It specifies the `[appname]` attribute, which should be the application's name in lowercase and without spaces. ```php 'my_application_name' ]; ``` -------------------------------- ### Configuración de Idioma por Defecto (config.php) Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Muestra cómo configurar el idioma por defecto de la aplicación en el archivo de configuración principal. ```php $config = [ 'default_lang' => 'es', // Idioma por defecto de la aplicación // ... otras configuraciones ]; ``` -------------------------------- ### Loading Core JavaScript Library Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates the essential step of loading the `core.js` file first in all main HTML files. This file contains critical framework utilities, including translation, link generation, and HTTP request functions. ```html ``` -------------------------------- ### Mandatory File Header Comment - PHP Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Ensures all PHP files include a mandatory header comment referencing the Vibe framework guidelines located at /.github/copilot-instructions.md. This comment serves as a crucial reference for AI agents and developers. ```php 'John Doe', 'email' => 'john.doe@example.com']; cache_set($cacheKey, $userData, 3600); // Cache for 1 hour (3600 seconds) // Example of getting a cache entry $cachedUserData = cache_get($cacheKey); if ($cachedUserData === null) { // Cache miss: retrieve data from the source (e.g., database) $userData = fetch_user_data_from_database($userId); // Store the retrieved data in cache cache_set($cacheKey, $userData, 3600); echo 'Data fetched from source and cached.'; } else { // Cache hit: use the cached data $userData = $cachedUserData; echo 'Data retrieved from cache.'; } print_r($userData); ``` -------------------------------- ### PHP Translation Key Naming Best Practices Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates recommended and discouraged naming conventions for translation keys in PHP. Emphasizes descriptive and hierarchical names for better organization and maintainability. ```php // ✅ Bueno 'auth_login_title', 'user_profile_button', 'dashboard_welcome_message' // ❌ Malo 'title', 'button', 'message' ``` -------------------------------- ### Perform HTTP GET Requests using libs_devops Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text The http_get function from libs_devops performs GET requests to a specified URL. It supports optional GET parameters and custom HTTP headers. The function returns an array containing success status, response data, HTTP code, and error messages if any. ```php /** * Realiza una petición HTTP GET * @param string $url URL de destino * @param array $params Parámetros GET opcionales * @param array $headers Headers HTTP opcionales * @return array */ public function fetch_api_data() { $devops = $this->main_object->libs_devops; // GET simple $result = $devops->http_get('https://api.example.com/users'); // GET con parámetros $result = $devops->http_get( 'https://api.example.com/users', ['limit' => 10, 'page' => 1] ); // GET con headers personalizados $result = $devops->http_get( 'https://api.example.com/users', [], ['Authorization' => 'Bearer token123', 'User-Agent' => 'MyApp/1.0'] ); if ($result['success']) { $data = $result['data']; $http_code = $result['http_code']; // Procesar datos... } else { $this->main_object->log->error("HTTP GET failed: " . $result['error']); } } ``` ```php public function get_weather_data($city) { $devops = $this->main_object->libs_devops; $result = $devops->http_get( 'https://api.weather.com/v1/current', ['city' => $city, 'units' => 'metric'], ['API-Key' => 'your-api-key'] ); if ($result['success']) { $weather = json_decode($result['data'], true); return $weather; } return null; } ``` ```php public function validate_vat_number($vat) { $devops = $this->main_object->libs_devops; $result = $devops->http_get( 'https://api.vatlayer.com/validate', ['vat_number' => $vat, 'access_key' => 'your-key'] ); if ($result['success']) { $validation = json_decode($result['data'], true); return $validation['valid'] ?? false; } return false; } ``` -------------------------------- ### Smarty Template System Usage in PHP Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates the mandatory methods for interacting with the Smarty templating engine within PHP controllers. Ensures proper variable assignment and template rendering or fetching. ```php main_object->smarty_assign('key', 'value'); // Displaying a layout template $this->main_object->display_layout('path/to/template.html'); // Fetching rendered HTML to assign to a variable $rendered_html = $this->main_object->smarty_fetch('path/to/template.html'); ?> ``` -------------------------------- ### AJAX Setup for CSRF Token in JavaScript Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Details the requirement for a global AJAX setup in JavaScript to automatically include the X-CSRF-Token header in POST, PUT, and DELETE requests. This ensures security for AJAX operations. ```javascript // Example of global ajaxSetup (specific implementation may vary based on library like jQuery) // $.ajaxSetup({ // headers: { // 'X-CSRF-Token': '{{csrftoken}}' // This token would typically be obtained from the server or a meta tag // } // }); ``` -------------------------------- ### PHP Database Query with Context Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates the correct way to perform a database query in PHP using the 'libs_devops' library. It highlights that the database context ('dbctx.seedbox.rw') must be passed directly to the 'db_query' method, not configured globally. ```php // En un controlador $devops = $this->main_object->libs_devops; $db_context = 'dbctx.seedbox.rw'; // Se especifica aquí $sql = "SELECT * FROM my_project.users LIMIT 10"; $result = $devops->db_query($db_context, $sql); ``` -------------------------------- ### Mandatory File Header Comment - HTML Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Ensures all HTML files include a mandatory header comment referencing the Vibe framework guidelines located at /.github/copilot-instructions.md. This comment is essential for maintaining consistency and providing AI agents with project context. ```html ``` -------------------------------- ### Bash Command to View Project-Specific Logs Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates how to view real-time logs for a specific project on the remote server using `ssh` and `tail -f`. It dynamically includes the current date and project name in the log file path. ```bash # Log específico del proyecto ssh [SSH_USER]@dev03.internalserver.cloudioo.org \ "tail -f /var/log/php/$(date +%Y%m%d)_[PROJECT_NAME].log" # Ejemplo con root: ssh root@dev03.internalserver.cloudioo.org \ "tail -f /var/log/php/$(date +%Y%m%d)_my_project.log" ``` -------------------------------- ### Project Configuration File (config.php) Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This PHP code snippet shows the structure of the main configuration file for a project. It includes essential settings like application name, default language, and root URL, emphasizing that database contexts should not be configured here. ```php '[PROJECT_NAME]', // Minúsculas, sin espacios // Multiidioma 'default_lang' => '[en|es|fr]', // Idioma por defecto // URLs 'url_root' => 'http://[PROJECT_NAME].vibe.cloudioo.org/', // Cache (si aplica) 'cache_ttl' => 3600, // 1 hora por defecto 'cache_enabled' => true ]; // Nota: NO configurar db_context ni db_name aquí // Los contextos de BD se pasan directamente en las llamadas a libs_devops // Ejemplo: $devops->db_query('dbctx.server.rw', $sql); ?> ``` -------------------------------- ### PHP: Execute DDL commands using db_exec Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Provides an example of executing Data Definition Language (DDL) commands or write operations like DELETE using the `db_exec` function. It takes the database context and the SQL command as input and returns a success status. ```php public function setup_test_table() { $devops = $this->main_object->libs_devops; $db_context = "dbctx.apps.ope.rw"; $sql = "CREATE TABLE tmp_vibe_testunits (id INT PRIMARY KEY, test_name VARCHAR(100))"; $result = $devops->db_exec($db_context, $sql); if ($result['success']) { // La tabla ha sido creada } } ``` -------------------------------- ### Correct and Incorrect URL Usage Examples in JavaScript Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This snippet demonstrates the proper and improper use of `applink()` and `publiclink()` functions. It highlights that `applink()` and `publiclink()` should only be used for internal project URLs and local static assets, respectively. External URLs should be used directly. ```javascript // ✅ CORRECT - Internal project URLs const userUrl = applink('users/list'); const cssUrl = publiclink('css/styles.css'); // ✅ CORRECT - Complete external URLs const apiUrl = 'https://api.example.com/users'; const cdnCss = 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/css/bootstrap.min.css'; // ❌ INCORRECT - Do not use applink/publiclink for external URLs const badUrl = applink('https://external-site.com'); // ❌ WRONG const badCdn = publiclink('https://cdn.example.com/file.css'); // ❌ WRONG ``` -------------------------------- ### Accessing Configuration Settings in PHP Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This PHP code snippet demonstrates how to access application configuration settings using the `libs_helper` library, which is available through `$this->main_object`. It shows how to retrieve specific configuration values and the entire configuration array. ```php public function show_settings() { $helper = $this->main_object->libs_helper; // Obtener un valor específico de la configuración $app_name = $helper->get_config('appname'); $debug_mode = $helper->get_config('debug'); // Obtener toda la configuración como un array $all_config = $helper->get_all_config(); // Asignar a la plantilla $this->main_object->smarty_assign('app_name', $app_name); $this->main_object->smarty_assign('all_settings', $all_config); } ``` -------------------------------- ### Endpoint para Cambio de Idioma (drivers/layout/layout.php) Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Implementación de un endpoint en PHP para manejar el cambio de idioma del usuario. Recibe el código de idioma, lo establece y redirige al usuario a la página solicitada. ```php class section_layout { public function setlang() { $helper = $this->main_object->libs_helper; $lang = $this->main_object->param('lang'); $redirect = $this->main_object->param('redirect'); if ($lang && $helper->set_language($lang)) { $redirect_url = $redirect ? urldecode($redirect) : applink('home/home'); header("Location: {$redirect_url}"); exit(); } else { $helper->show_error("Invalid language code", 400); } } } ``` -------------------------------- ### Mandatory File Header Comment - CSS/JavaScript Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Ensures all CSS and JavaScript files include a mandatory header comment referencing the Vibe framework guidelines located at /.github/copilot-instructions.md. This header is vital for AI detection and project-wide consistency. ```css /* ⚠️ IMPORTANTE: Sigue las directrices del framework Vibe. Ver: /.github/copilot-instructions.md [Componente] - [Descripción] Vibe Framework Implementation */ ``` -------------------------------- ### JavaScript para Cambio de Idioma Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Funciones de JavaScript para facilitar el cambio de idioma en el lado del cliente. Permiten redirigir a la URL de cambio de idioma o mantener la página actual. ```javascript function changeLanguage(lang) { window.location.href = applink('layout/setlang?lang=' + lang); } // Cambiar idioma y mantener la página actual function changeLanguageAndReturn(lang) { const currentPage = window.location.pathname + window.location.search; window.location.href = applink('layout/setlang?lang=' + lang + '&redirect=' + encodeURIComponent(currentPage)); } ``` -------------------------------- ### PHP: Get multiple database rows using db_query Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Explains how to fetch multiple rows from a database using the `db_query` function. It accepts the database context and a SQL query, returning the success status, an array of data, and the total count of rows. ```php public function get_all_users() { $devops = $this->main_object->libs_devops; $db_context = "dbctx.apps.ope.rw"; $sql = "SELECT id, test_name FROM tmp_vibe_testunits ORDER BY id"; $result = $devops->db_query($db_context, $sql); if ($result['success']) { $all_users = $result['data']; $total_users = $result['count']; // Lógica adicional... } } ``` -------------------------------- ### CSS: Home Page Styling and Animations Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Contains CSS rules for styling the home page, including layout for the main container, styling for a primary button with a gradient background and hover effect, and a fade-in animation for content loaded. ```css /* Estilos específicos de la página home */ #main-container { padding: 2rem; max-width: 1200px; margin: 0 auto; } .primary-button { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; transition: transform 0.2s ease; } .primary-button:hover { transform: translateY(-2px); } .loaded { opacity: 1; animation: fadeIn 0.5s ease-in; } ``` -------------------------------- ### PHP General Coding Conventions Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This section outlines general coding conventions for PHP, including naming conventions for methods, variables, classes, and files. It also specifies formatting rules such as indentation, the use of ` {{$config.appname}} - {{t key='page_title'}}
{{$content}} ``` -------------------------------- ### JavaScript: Home Page Functionality and Event Handling Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Provides JavaScript code for a home page, including functions for initialization, event handling on a button click, and updating dynamic content. It demonstrates DOM manipulation and event listeners, ensuring scripts run after the DOM is ready. ```javascript // Funciones específicas de la página home function initHomePage() { document.getElementById('action-btn').addEventListener('click', handleAction); updateDynamicContent(); } function handleAction() { const message = t('action_completed'); alert(message); } function updateDynamicContent() { document.getElementById('main-container').classList.add('loaded'); } // Inicializar cuando la página esté lista document.addEventListener('DOMContentLoaded', initHomePage); ``` -------------------------------- ### PHP: Get a single database row using db_get_row Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Illustrates how to retrieve a single row from a database using the `db_get_row` function. This function takes the database context and a SQL query as input, returning the success status and the row data if found. ```php public function get_user($user_id) { $devops = $this->main_object->libs_devops; $db_context = "dbctx.apps.ope.rw"; $sql = "SELECT * FROM tmp_vibe_testunits WHERE id = " . $devops->db_quote($user_id); $result = $devops->db_get_row($db_context, $sql); if ($result['success']) { $user_data = $result['data']; // Lógica adicional... } } ``` -------------------------------- ### HTML Structure: Inline vs. Separated Elements Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates the incorrect practice of embedding JavaScript and CSS directly within HTML elements and contrasts it with the recommended approach of separating these concerns into distinct files. ```html
``` -------------------------------- ### HTML: Clean Structure and Script/Link Placement Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Presents a clean HTML structure for a home page, emphasizing the correct placement of the core JavaScript file in the head and section-specific JavaScript at the end of the body. It also shows how to link external CSS files. ```html {{$app_name}} - {{t key='home_title'}}

{{t key='welcome_title'}}

``` -------------------------------- ### SSH Command to Monitor Project Logs Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text A command to establish an SSH connection to the development server and continuously monitor the project's specific log file in real-time. This is crucial for observing application behavior and errors as they occur. ```bash # Ver logs del proyecto directamente ssh root@dev03.internalserver.cloudioo.org \ "tail -f /var/log/php/$(date +%Y%m%d)_my_docs.log" ``` -------------------------------- ### SQL Table Naming and Index Convention Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Defines the standard conventions for naming tables and defining essential fields and indexes in the database. This includes a descriptive prefix for tables and mandatory timestamp fields with corresponding indexes. ```sql -- Nomenclatura: -- Prefijo descriptivo: [prefix]_table_name -- Ejemplo: pr_doc_sources, usr_profiles -- Campos obligatorios: -- [prefix]_ts_created - Fecha de creación (DATETIME) -- [prefix]_ts_updated - Fecha de actualización (DATETIME) -- Indexes obligatorios: CREATE INDEX idx_[prefix]_ts_created ON [table_name] ([prefix]_ts_created); CREATE INDEX idx_[prefix]_ts_updated ON [table_name] ([prefix]_ts_updated); -- Actualización automática: [prefix]_ts_updated DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ``` -------------------------------- ### JavaScript AJAX and Translation Function Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Illustrates how to integrate AJAX calls and use the translation function `t()` in JavaScript for dynamic content loading and multi-language support. It emphasizes loading `core.js` and following best practices for client-side interactions. ```javascript // Ensure core.js is loaded before this script // Example of using the translation function console.log(t('hello_world')); // Outputs translated string for 'hello_world' // Example of an AJAX call using fetch API (assuming a backend endpoint '/api/data') fetch('/api/data') .then(response => response.json()) .then(data => { console.log('Data received:', data); // Update UI with translated strings document.getElementById('greeting').innerText = t('greeting_message') + ', ' + data.username; }) .catch(error => { console.error('Error fetching data:', error); document.getElementById('error-message').innerText = t('error_loading_data'); }); ``` -------------------------------- ### PHP HTTP Request Functions Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates the use of `http_get` and `http_post` for making external HTTP requests. It explicitly prohibits the use of the native cURL functions, enforcing the framework's abstractions for consistency and security. ```php // Example of making an HTTP GET request $response_get = http_get('https://api.example.com/data'); // Example of making an HTTP POST request $post_data = ['key' => 'value']; $response_post = http_post('https://api.example.com/submit', $post_data); ``` -------------------------------- ### Variables Globales de Traducción en Plantillas HTML Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Lista de variables globales que el sistema de traducciones pone a disposición de todas las plantillas Smarty, como el idioma actual y el array completo de traducciones. ```html {{$current_lang}} {{$translations}} ``` -------------------------------- ### Smarty Template Engine Syntax in HTML Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Illustrates the correct syntax for using Smarty tokens and variables within HTML template files. All Smarty elements must be enclosed in double curly braces {{...}}. ```html {{$app_name}} - Inicio

Bienvenido, {{if $user_data}}{{$user_data.name}}{{else}}Invitado{{/if}}

``` -------------------------------- ### PHP Dynamic Translation with sprintf Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Shows how to handle dynamic text within translations in PHP. It involves defining a translation string with a placeholder (`%s`) in the language file and then using `sprintf` in the controller to insert the variable content. ```php // En el archivo de traducción 'welcome_user' => 'Bienvenido, %s', // En el controlador $message = sprintf($helper->translate('welcome_user'), $username); ``` -------------------------------- ### HTML Translation Plugin Usage (Recommended) Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Illustrates the preferred method of using the translation plugin `{{t key='...'}}` in HTML templates versus accessing translations directly via `{{$translations.}}`. The plugin method is recommended for consistency and adherence to framework patterns. ```html

{{t key='welcome_title'}}

{{$translations.welcome_title}}

``` -------------------------------- ### Plugin Smarty {t} para Plantillas HTML Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demostración del uso del plugin `{t}` de Smarty directamente en las plantillas HTML para mostrar traducciones. Soporta claves, idiomas específicos, valores por defecto y uso dinámico. ```html {{t key='page_title'}}

{{t key='welcome_title'}}

{{t key='login_button' lang='en'}}

{{t key='optional_text' default='Texto opcional'}} {{foreach $menu_items as $item}}
  • {{t key=$item.text_key}}
  • {{/foreach}} ``` -------------------------------- ### Uso de Traducciones en Controladores PHP Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Ejemplo de cómo interactuar con el sistema de traducciones desde un controlador utilizando `libs_helper`. Permite obtener el idioma actual, establecer un idioma específico y traducir cadenas. ```php public function show_dashboard() { $helper = $this->main_object->libs_helper; // Obtener el idioma actual del usuario $current_lang = $helper->get_current_language(); // 'es', 'en', 'fr' // Establecer un idioma específico (opcional) $helper->set_language('en'); // Obtener traducciones $page_title = $helper->translate('dashboard_title'); $welcome_msg = $helper->translate('welcome_message', 'es'); // Forzar idioma específico $fallback_text = $helper->translate('missing_key', null, 'Texto por defecto'); // Asignar variables a la plantilla $this->main_object->smarty_assign('page_title', $page_title); $this->main_object->smarty_assign('current_lang', $current_lang); $this->main_object->display_layout('drivers/dashboard/dashboard.html'); } ``` -------------------------------- ### SQL Query Format with Database Prefix Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Illustrates the mandatory format for SQL queries when using MCP (MySQL Control Panel) or similar tools. It emphasizes the requirement to include the database name as a prefix to table names for clarity and correctness. ```sql -- ✅ CORRECTO (con prefijo de base de datos) SELECT * FROM [DB_NAME].[table_name] LIMIT 10; -- ❌ INCORRECTO (sin prefijo de base de datos) SELECT * FROM [table_name]; ``` -------------------------------- ### PHP Database CRUD Operations Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Details the expected interface for database interactions within the Vibe framework, covering standard Create, Read, Update, and Delete (CRUD) operations. It uses a `dbctx` object for managing these operations. ```php // Assuming $dbctx is an instance of the database context object // Insert a new record $dbctx->insert('table_name', ['column1' => 'value1', 'column2' => 'value2']); // Update existing records $dbctx->update('table_name', ['column1' => 'new_value'], ['id' => 1]); // Get a single record by ID $record = $dbctx->get('table_name', 1); // Query records with conditions $results = $dbctx->query('SELECT * FROM table_name WHERE status = ?', ['active']); // Execute a raw SQL statement $dbctx->exec('DELETE FROM table_name WHERE created_at < ?', [date('Y-m-d', strtotime('-30 days'))]); ``` -------------------------------- ### Archivos de Traducción PHP (es.php) Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Ejemplo de la estructura de archivos de traducción en formato PHP. Cada archivo corresponde a un idioma y contiene un array asociativo de claves y sus traducciones. ```php // lang/es.php return [ 'welcome_title' => 'Bienvenido a la Aplicación', 'login_button' => 'Iniciar Sesión', 'logout_button' => 'Cerrar Sesión', 'save_button' => 'Guardar', 'cancel_button' => 'Cancelar', // Agrupadas por sección para mejor organización 'auth_login_title' => 'Acceso al Sistema', 'auth_register_title' => 'Registro de Usuario', 'user_profile_title' => 'Perfil de Usuario', ]; ``` -------------------------------- ### PHP: Insert a new database record using db_insert Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Demonstrates how to insert a new record into a database table using the `db_insert` function from `libs_devops`. It takes a database context, table name, and an array of data as input, returning the success status and the ID of the inserted record. ```php public function create_user() { $devops = $this->main_object->libs_devops; $db_context = "dbctx.apps.ope.rw"; $new_user_data = [ 'test_name' => 'nuevo_usuario', 'test_value' => 'Valor de prueba' ]; $result = $devops->db_insert($db_context, 'tmp_vibe_testunits', $new_user_data); if ($result['success']) { $new_id = $result['insert_id']; // Lógica adicional... } } ``` -------------------------------- ### PHP Controller Structure and Rendering Pattern Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Defines the standard structure for a PHP controller class, including mandatory library access methods and a strict pattern for fetching and displaying template content using Smarty. It highlights that each public function must match a URL event and emphasizes the use of a central layout for rendering. ```php class section_[nombre] { // ⚠️ CRÍTICO: Cada función pública debe coincidir con el parámetro "event" de la URL public function [evento]() { // ✅ ACCESO CORRECTO A LIBRERÍAS (OBLIGATORIO) $devops = $this->main_object->libs_devops; $helper = $this->main_object->libs_helper; // Lógica del controlador $data = $this->processLogic(); // Asignación a la sección específica $this->main_object->smarty_assign('section_data', $data); $this->main_object->smarty_assign('page_title', 'Título de la Página'); // ⚠️ PATRÓN OBLIGATORIO DE RENDERIZADO: // PASO 1: Renderizar la plantilla de la sección $section_content = $this->main_object->smarty_fetch('drivers/[section]/[section].html'); // PASO 2: Asignar el contenido al token del layout $this->main_object->smarty_assign('content', $section_content); // PASO 3: Mostrar el layout principal $this->main_object->display_layout('drivers/layout/layout.html'); } } ``` ```php // ❌ MAL: Renderizar directamente la sección $this->main_object->display_layout('drivers/home/home.html'); // ❌ MAL: No usar el layout centralizado $this->main_object->smarty->display('drivers/home/home.html'); ``` -------------------------------- ### PHP S3 File Handling Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Provides an overview of how to manage files stored in Amazon S3 buckets within the Vibe framework. It covers handling public and private files, as well as generating temporary URLs for secure, time-limited access. ```php // Assuming $s3Client is configured and initialized // Upload a public file $s3Client->putObject([ 'Bucket' => 'your-bucket-name', 'Key' => 'public/path/to/your/file.jpg', 'SourceFile' => '/local/path/to/your/file.jpg', 'ACL' => 'public-read' ]); // Get a signed URL for a private file $cmd = $s3Client->getCommand('GetObject', [ 'Bucket' => 'your-bucket-name', 'Key' => 'private/path/to/your/document.pdf' ]); $request = $s3Client->createPresignedRequest($cmd, '+15 minutes'); $signedUrl = (string) $request->getUri(); // Example of outputting a public URL echo 'Public URL: ' . $s3Client->getObjectUrl('your-bucket-name', 'public/path/to/your/file.jpg'); ``` -------------------------------- ### Correct and Incorrect Inline Styles and Scripts Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Highlights the strict rule against using inline CSS ( ``` -------------------------------- ### PHP Error Logging and Return Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Illustrates the mandated method for error handling in the Vibe framework. It prohibits the use of `try-catch` blocks and exceptions. Instead, errors must be reported using `log->error($message)`, and functions should return `false` or `null` to indicate failure. ```php // Example of logging an error and returning null if (!some_condition) { log->error('An error occurred because some_condition was not met.'); return null; } ``` -------------------------------- ### Frontend: URL and Translation Helpers Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Utilize the provided Smarty and JavaScript helpers for generating internal URLs and translating static text. Use `{{applink url='/path'}}` or `applink('/path')` for internal links, `{{publiclink url='/path'}}` or `publiclink('/path')` for static assets, and translation functions `{{t key='key_name'}}` or `t('key_name')` for text. External URLs should be absolute. ```smarty My Profile Logo

    {{t key='page_title'}}

    ``` ```javascript // Assuming applink and publiclink are globally available or imported // Internal link const profileLink = applink('/users/profile'); // Static asset const logoPath = publiclink('/images/logo.png'); // Translation (assuming t is globally available or imported) document.getElementById('page-title').innerText = t('page_title'); ``` -------------------------------- ### SSH Command to Tail PHP Logs with Grep Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This command connects to a development server via SSH and tails the last 100 lines of a PHP-FPM error log, filtering for lines related to a specific project name. It's useful for debugging by providing recent error context. ```bash ssh [SSH_USER]@dev03.internalserver.cloudioo.org \ "tail -n 100 /var/log/php/$(date +%Y%m%d)_php-fpm-error.log | grep -B 5 -A 10 '[PROJECT_NAME]'" ``` -------------------------------- ### Database Coding Conventions and Result Handling in PHP Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Guidelines for writing SQL queries in PHP, emphasizing readability through multiline formatting and clear aliases. It specifies using double quotes for SQL strings and adhering to the convention that all `libs_devops` methods return an associative array, requiring a check of `$result['success']` before accessing `$result['data']`. ```php #### **Conventions for Databases** * **Readability:** Write SQL queries in a multiline formatted `$sql` variable for clarity. * **Quotes:** Use double quotes (`"`) for SQL query text strings. * **Aliases:** Use short, clear aliases in queries (e.g., `u` for `users`, `p` for `products`). * **Return:** All methods of `libs_devops` return an associative array. You **MUST ALWAYS** check the status with `$result['success']` before attempting to access `$result['data']`. ``` -------------------------------- ### Generate Internal Project URLs with applink() in JavaScript Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text The `applink(uri)` JavaScript function generates internal URLs for navigation within the project, such as user lists or editing specific records. It shares the same features as `publiclink()` regarding translations, caching, and PHP mode management. ```javascript const userUrl = applink('users/list'); const editUrl = applink('admin/users/edit?id=123'); window.location.href = applink('home/dashboard'); ``` -------------------------------- ### Update DOM Dynamically with Translated Text and Project Links in JavaScript Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text This JavaScript function `updateInterface()` shows how to dynamically update the content of DOM elements using translated text (via `t()`) and generated URLs for stylesheets and navigation (via `publiclink()` and `applink()`). ```javascript function updateInterface() { document.getElementById('title').textContent = t('dynamic_title'); document.getElementById('saveBtn').textContent = t('save_button'); // Dynamically change a CSS file document.getElementById('stylesheet').href = publiclink('css/theme-dark.css'); // Redirect to another page window.location.href = applink('users/profile'); } ``` -------------------------------- ### Smarty Template Tokens Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Shows the usage of essential Smarty template tokens within Vibe framework's frontend development. These tokens provide access to application links, public assets, CSRF tokens, translations, and configuration values directly in the HTML templates. ```smarty User Profile Logo

    {{t key='welcome_message'}}

    Application Mode: {{config key='environment'}}

    ``` -------------------------------- ### PHP Database Operations with libs_devops Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Illustrates the mandatory use of the `libs_devops` library for all database interactions within the Vibe framework. It highlights the requirement for a `$dbcontext` to specify the database connection and the use of `$devops->db_quote()` for sanitizing dynamic parameters to prevent SQL injection vulnerabilities. Direct database access is strictly prohibited. ```php // Mandatory use of libs_devops methods for database operations. // Example of sanitizing parameters: $sanitized_param = $devops->db_quote($user_input); // Example of specifying database context: // $db_context = 'dbctx.apps.ope.rw'; // or 'dbctx.reporting.ope.ro' // Perform database operation using $devops and $db_context ``` -------------------------------- ### PHP: Update a database record using db_update Source: https://project_rules.vibe.cloudioo.org/docs/get/fetch_preset=vibe_docs&format=text Shows how to update an existing database record using the `db_update` function. It requires the database context, table name, an array of data to update, and a WHERE clause to specify the target row. It returns the success status and the number of affected rows. ```php public function update_user_value($user_id, $new_value) { $devops = $this->main_object->libs_devops; $db_context = "dbctx.apps.ope.rw"; $update_data = ['test_value' => $new_value]; $where_clause = "id = " . $devops->db_quote($user_id); $result = $devops->db_update($db_context, 'tmp_vibe_testunits', $update_data, $where_clause); if ($result['success']) { $affected_rows = $result['affected_rows']; // Lógica adicional... } } ```