├── style.css ├── .htaccess ├── autoload.php ├── images ├── image00.jpg ├── image01.png ├── image02.png ├── image03.png ├── image04.png ├── image05.png ├── image06.png ├── image07.jpg ├── image08.png ├── image09.png ├── image10.png ├── image11.jpg ├── image12.png ├── image13.png ├── welcome-page.jpg ├── kumbia-url-anatomy.png ├── kumbiaphp-greetings.png ├── test-welcome-message.jpg ├── successful-installation.jpg ├── kumbia-url-anatomy-params.png ├── kumbiaphp-greetings-date.png ├── kumbiaphp-greetings-goodbye.png ├── incorrect-number-of-parameters.jpg ├── incorrect-number-of-parameters.png ├── kumbiaphp-greetings-hello-cachi.png ├── kmbiaphp-blog-example-using-call.jpg └── bypass-incorrect-number-of-parameters.jpg ├── crowdin.yml ├── composer.json ├── .gitignore ├── es ├── toc.yaml ├── readme.md ├── model.md ├── scaffold.md ├── front-controller.md ├── to-install.md ├── console.md ├── crud.md ├── installing-kumbiaphp-apache-nginx.md ├── preface.md ├── configuration.md ├── first-app.md ├── mvc.md ├── appendix.md └── controller.md ├── en ├── readme.md ├── model.md ├── scaffold.md ├── to-install.md ├── front-controller.md ├── mvc.md ├── console.md ├── crud.md ├── preface.md ├── configuration.md ├── installing-kumbiaphp-apache-nginx.md ├── first-app.md ├── controller.md ├── appendix.md ├── parent-class.md └── index.md ├── .github └── FUNDING.yml ├── Markdown.php ├── index.php ├── toc.php ├── readme.md └── prism.css /style.css: -------------------------------------------------------------------------------- 1 | body{margin:auto;width:80%} -------------------------------------------------------------------------------- /.htaccess: -------------------------------------------------------------------------------- 1 | RewriteEngine on 2 | RewriteRule ^(.+\.md)$ index.php?file=$1 [L] -------------------------------------------------------------------------------- /autoload.php: -------------------------------------------------------------------------------- 1 | $id); 8 | return $array; 9 | } 10 | 11 | 12 | 13 | static public function generateId($title){ 14 | return str_replace(' ', '-', 15 | str_replace(array('(', ')', '?', '¿'), '', strtolower($title)) 16 | ); 17 | } 18 | 19 | protected function identifyLink($Excerpt){ 20 | $r = parent::identifyLink($Excerpt); 21 | if(isset($r['element']['name']) && $r['element']['name'] == 'img'){ 22 | $r['element']['attributes']['src'] = '/doc/'.$r['element']['attributes']['src']; 23 | } 24 | return $r; 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /index.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | 12 | 13 | . 14 | 15 | <?php echo $title[2];?> 16 | 17 | 18 | 19 | 20 |
21 | text(toc_file($file, FALSE));?> 22 |
23 | 24 | 25 | text($text);?> 26 | 27 | 28 | -------------------------------------------------------------------------------- /toc.php: -------------------------------------------------------------------------------- 1 | $value) { 34 | $tab = str_replace('#', ' ', substr($value[1], 1)); 35 | $title = trim($value[2]); 36 | $id = Markdown::generateId($title); 37 | $text .= "$tab- [$title]($path#$id)\n"; 38 | } 39 | return $text; 40 | } 41 | 42 | 43 | if(php_sapi_name() == "cli") { 44 | generate_toc($argc, $argv); 45 | } -------------------------------------------------------------------------------- /en/model.md: -------------------------------------------------------------------------------- 1 | # Models 2 | 3 | Models lies the logic of business (or application). Mistakenly, many people believe that the models are only for working with databases. 4 | 5 | Models can be of many types: 6 | 7 | - Create thumbnails of images 8 | - Consume and use webservices 9 | - Create payment gateways 10 | - Use LDAP 11 | - Send mails or check mail servers 12 | - Interact with the local file system or via FTP, or any other protocol 13 | - etc etc 14 | 15 | ## How to use models 16 | 17 | The models represent the application logic, and are a fundamental part for the moment that develops an application, a good use of these provides us a great power when needed scale, maintain and reuse the code in an application. 18 | 19 | A bad use of models is usually only leave the file with the class declaration and generate all the logic in the controller. This practice brings as consequence that first controller is hardly understandable for someone that tries to add or change something in that functionality, secondly what little you can refuse the code on other controllers. That leads to repeat code that does the same thing on another controller. 20 | 21 | Based on this principle, the controllers should not contain any logic, only handle deal with the requests of the users and request such information from the models. With this we guarantee a good use of the [MVC](https://es.wikipedia.org/wiki/Modelo-vista-controlador). -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # KumbiaPHP Framework Documentation 2 | 3 | Welcome to the official documentation for KumbiaPHP Framework, a powerful, lightweight, and easy-to-use PHP framework 4 | focused on productivity and rapid development. 5 | 6 | ## Available Languages 7 | 8 | - [Documentación en Español v1.0](es/) - Complete documentation in Spanish 9 | - [English Manual v1.0](en/) - English documentation (looking for contributors!) 10 | 11 | ## About This Documentation 12 | 13 | This repository contains comprehensive documentation for KumbiaPHP Framework, covering everything from installation and 14 | basic concepts to advanced usage and components. The documentation is organized by language and provides a step-by-step 15 | guide to help you build web applications efficiently with KumbiaPHP. 16 | 17 | ## Documentation Structure 18 | 19 | Each language section includes: 20 | - Introduction to KumbiaPHP concepts 21 | - Installation guides 22 | - Getting started tutorials 23 | - Detailed component documentation 24 | - MVC architecture explanations 25 | - Examples and best practices 26 | 27 | ## How to Contribute 28 | 29 | 1. Fork this repository 30 | 2. Make your changes or additions 31 | 3. Submit a pull request 32 | 33 | ## Official KumbiaPHP Resources 34 | 35 | - [KumbiaPHP Website](https://kumbiaphp.com) 36 | - [GitHub Repository](https://github.com/KumbiaPHP/KumbiaPHP) 37 | - [Community Forum](https://groups.google.com/group/kumbia) 38 | -------------------------------------------------------------------------------- /es/model.md: -------------------------------------------------------------------------------- 1 | # Modelos 2 | 3 | En los Modelos reside la lógica de negocio (o de la aplicación). 4 | Equivocadamente, mucha gente cree que los modelos son solo para trabajar con 5 | las bases de datos. 6 | 7 | Los modelos puedes ser de muchos tipos: 8 | 9 | * Crear miniaturas de imágenes 10 | * Consumir y usar webservices 11 | * Crear pasarelas Scaffold de pago 12 | * Usar LDAP 13 | * Enviar mails o consultar servidores de correo 14 | * Interactuar con el sistema de ficheros local o vía FTP, o cualquier otro protocolo 15 | * etc etc 16 | 17 | ## Como usar los modelos 18 | 19 | Los Modelos representan la lógica de la aplicación, y son parte fundamental 20 | para el momento que se desarrolla una aplicación, un buen uso de estos nos 21 | proporciona un gran poder al momento que se necesita escalar, mantener y 22 | reusar código en una aplicación. 23 | 24 | Por lo general un mal uso de los modelos es sólo dejar el archivo con la 25 | declaración de la clase y generar toda la lógica en el controlador. Esta 26 | práctica trae como consecuencia que en primer lugar el controlador sea 27 | difícilmente entendible por alguien que intente agregar y/o modificar algo en 28 | esa funcionalidad, en segundo lugar lo poco que puedes rehusar el código en 29 | otros controladores. Eso conlleva a repetir código que hace lo mismo en 30 | otro controlador. 31 | 32 | Partiendo de este principio, los controladores NO deberían contener ningún 33 | tipo de lógica, sólo se encargan de atender las peticiones del usuarios y 34 | solicitar dicha información a los modelos. Con esto garantizamos un buen uso 35 | del [MVC](https://es.wikipedia.org/wiki/Modelo-vista-controlador). 36 | 37 | -------------------------------------------------------------------------------- /prism.css: -------------------------------------------------------------------------------- 1 | /* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+php+php-extras+bash+python+sql+http+ini+apacheconf */ 2 | /** 3 | * prism.js default theme for JavaScript, CSS and HTML 4 | * Based on dabblet (http://dabblet.com) 5 | * @author Lea Verou 6 | */ 7 | 8 | code[class*="language-"], 9 | pre[class*="language-"] { 10 | color: black; 11 | text-shadow: 0 1px white; 12 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 13 | direction: ltr; 14 | text-align: left; 15 | white-space: pre; 16 | word-spacing: normal; 17 | word-break: normal; 18 | line-height: 1.5; 19 | 20 | -moz-tab-size: 4; 21 | -o-tab-size: 4; 22 | tab-size: 4; 23 | 24 | -webkit-hyphens: none; 25 | -moz-hyphens: none; 26 | -ms-hyphens: none; 27 | hyphens: none; 28 | } 29 | 30 | pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, 31 | code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { 32 | text-shadow: none; 33 | background: #b3d4fc; 34 | } 35 | 36 | pre[class*="language-"]::selection, pre[class*="language-"] ::selection, 37 | code[class*="language-"]::selection, code[class*="language-"] ::selection { 38 | text-shadow: none; 39 | background: #b3d4fc; 40 | } 41 | 42 | @media print { 43 | code[class*="language-"], 44 | pre[class*="language-"] { 45 | text-shadow: none; 46 | } 47 | } 48 | 49 | /* Code blocks */ 50 | pre[class*="language-"] { 51 | padding: 1em; 52 | margin: .5em 0; 53 | overflow: auto; 54 | } 55 | 56 | :not(pre) > code[class*="language-"], 57 | pre[class*="language-"] { 58 | background: #f5f2f0; 59 | } 60 | 61 | /* Inline code */ 62 | :not(pre) > code[class*="language-"] { 63 | padding: .1em; 64 | border-radius: .3em; 65 | } 66 | 67 | .token.comment, 68 | .token.prolog, 69 | .token.doctype, 70 | .token.cdata { 71 | color: slategray; 72 | } 73 | 74 | .token.punctuation { 75 | color: #999; 76 | } 77 | 78 | .namespace { 79 | opacity: .7; 80 | } 81 | 82 | .token.property, 83 | .token.tag, 84 | .token.boolean, 85 | .token.number, 86 | .token.constant, 87 | .token.symbol, 88 | .token.deleted { 89 | color: #905; 90 | } 91 | 92 | .token.selector, 93 | .token.attr-name, 94 | .token.string, 95 | .token.char, 96 | .token.builtin, 97 | .token.inserted { 98 | color: #690; 99 | } 100 | 101 | .token.operator, 102 | .token.entity, 103 | .token.url, 104 | .language-css .token.string, 105 | .style .token.string { 106 | color: #a67f59; 107 | background: hsla(0, 0%, 100%, .5); 108 | } 109 | 110 | .token.atrule, 111 | .token.attr-value, 112 | .token.keyword { 113 | color: #07a; 114 | } 115 | 116 | .token.function { 117 | color: #DD4A68; 118 | } 119 | 120 | .token.regex, 121 | .token.important, 122 | .token.variable { 123 | color: #e90; 124 | } 125 | 126 | .token.important { 127 | font-weight: bold; 128 | } 129 | 130 | .token.entity { 131 | cursor: help; 132 | } 133 | 134 | -------------------------------------------------------------------------------- /en/scaffold.md: -------------------------------------------------------------------------------- 1 | # Scaffold 2 | 3 | ## Introduction 4 | 5 | To begin, it is important to know, that the Scaffold was used until the stable release 0.5 Kumbiaphp and that leaving Kumbiaphp version 1.0 Spirit beta 1 will leave aside, to create a new one more customizable and maintainable. 6 | 7 | Seeing the need and the facilities that the Scaffold provides applications support, Kumbiaphp development team returns to incorporate a new for your KumbiaPHP version beta 2, improving and simplifying the performance of the Scaffold for the Framework and that undoubtedly contributes to a breakthrough in any development application for users in using Kumbiaphp and advanced users, delivering to all a high range of possibilities. 8 | 9 | ## Concept 10 | 11 | Scaffold is a meta-programming method to build software applications that support database. This is a new technique supported by some frameworks like MVC (model-view - controller), where the programmer must write a specification type as it should be used the implementation of databases. The compiler then use this to generate a code that I can use the application to read, create, update and delete entries (something known as CRUD or ABM) database, trying to put templates as a Scaffold scaffolding) on which to build an application more powerful. 12 | 13 | Scaffolding is the evolution of generators codes of databases from more developed environments, such as CASE Generator for Oracle and other so many servers 4GL for services to customer. Scaffolding became popular thanks to the framework "Ruby on Rails", which has been adapted to other frameworks, including Django, Monorail, KumbiaPHP framework among others. 14 | 15 | ## Objective 16 | 17 | Creating a CRUD 100% functional with just 2 lines of code in my controller. 18 | 19 | KumbiaPHP takes as if by magic, the parameters listed in my table and weapon all the CRUD. 20 | 21 | ## Getting Started 22 | 23 | To make our first Scaffold, will use the same model working on the [CRUD to KumbiaPHP Beta2](http://wiki.kumbiaphp.com/Beta2_CRUD_en_KumbiaPHP_Framework), and has different menus. 24 | 25 | Model 26 | 27 | Create the model, as always pointing to the ActiveRecord class. 28 | 29 | [app]/models/menus.php: 30 | 31 | ```php 32 | ⚠️ **Warning** 6 | > 7 | > This installation is intended as a testing environment, designed for experimenting with KumbiaPHP on a local server. 8 | > It is **not** recommended for developing applications that will be deployed to production. 9 | 10 | ## Requirements 11 | 12 | As mentioned earlier, KumbiaPHP is very easy to use, and the requirements to run it are minimal. You only need a [**PHP 13 | version 8.0**](https://www.php.net/) interpreter or higher. 14 | 15 | ## Installation Steps 16 | 17 | 1. Download the KumbiaPHP compressed file from the downloads section at 18 | [kumbiaphp.com](http://www.kumbiaphp.com/blog/manuales-y-descargas/) to get the latest version of the framework. 19 | 20 | Make sure the file has the `.tgz` extension if you are using Linux, or `.zip` if you are using Windows; otherwise, it 21 | may not decompress properly. 22 | 23 | 2. Once downloaded, extract its contents into your preferred directory. 24 | To keep this manual consistent, we will assume the package has been extracted into a directory named `kumbiaphp/`, 25 | with a structure similar to the following: 26 | 27 | ``` 28 | kumbiaphp/ 29 | ├── core/ 30 | ├── vendor/ 31 | └── default/ 32 | ├── app/ 33 | ├── public/ 34 | │ ├── .htaccess 35 | │ └── index.php 36 | ├── .htaccess 37 | └── index.php 38 | ``` 39 | 40 | 3. Open a terminal and navigate to the `default/app` directory: 41 | 42 | ```bash 43 | cd kumbiaphp/default/app 44 | ``` 45 | 46 | 4. Run the included development server: 47 | 48 | ```bash 49 | ./bin/phpserver 50 | ``` 51 | 52 | This command starts a local web server using PHP’s built-in server, allowing you to run the application immediately 53 | without additional configuration. 54 | 55 | 5. Open your web browser and go to: 56 | 57 | ``` 58 | http://0.0.0.0:8001/ 59 | ``` 60 | 61 | or 62 | 63 | ``` 64 | http://127.0.0.1:8001/ 65 | ``` 66 | 67 | If everything went well, you should see a welcome page indicating that the installation was successful. 68 | 69 | ![Successful installation](../images/successful-installation.jpg) 70 | 71 | > ℹ️ **Information** 72 | > 73 | > **Alternative: Using Apache or Nginx** — If you prefer, you can use a traditional web server such as Apache or Nginx. 74 | > For that, refer to the section 75 | > [Installing KumbiaPHP on Web Servers (Apache and Nginx)](installing-kumbiaphp-apache-nginx.md), where you will find 76 | > detailed instructions. 77 | 78 | ## Application Modes 79 | 80 | KumbiaPHP offers two execution modes for an application, defined in the 81 | [default/public/index.php](https://github.com/KumbiaPHP/KumbiaPHP/blob/master/default/public/index.php) file: 82 | 83 | ### Development Mode 84 | 85 | This is the default mode. The `PRODUCTION` constant is set to `false`: 86 | 87 | ```php 88 | const PRODUCTION = false; 89 | ``` 90 | 91 | In this mode, KumbiaPHP’s cache is disabled. Any changes made to database tables or fields, as well as to views, are 92 | reflected immediately. 93 | 94 | ### Production Mode 95 | 96 | To enable it, change the `PRODUCTION` constant to `true`: 97 | 98 | ```php 99 | const PRODUCTION = true; 100 | ``` 101 | 102 | In this mode, KumbiaPHP enables its caching system, storing key information such as database metadata (table names, 103 | fields, etc.) and any views you choose to cache, improving performance. 104 | 105 | > ⚠️ **Warning** 106 | > 107 | > When changing `PRODUCTION` from `false` to `true`, you must manually delete the contents of the cache directory 108 | > located at `default/app/temp/cache/` to ensure that metadata is refreshed correctly. If you don’t, you may encounter 109 | > errors when saving or displaying information. 110 | -------------------------------------------------------------------------------- /es/scaffold.md: -------------------------------------------------------------------------------- 1 | # Scaffold 2 | 3 | ## Introducción 4 | 5 | Para empezar es importante saber, que el Scaffold se utilizo hasta la versión 6 | estable de Kumbiaphp 0.5 y que al salir la versión de Kumbiaphp 1.0 Spirit 7 | beta 1 se dejo a un lado, hasta crear uno nuevo mas configurable y mantenible. 8 | 9 | Viendo la necesidad y las facilidades que el Scaffold proporciona al apoyo de 10 | aplicaciones, el equipo de desarrollo de Kumbiaphp vuelve a incorporar un 11 | nuevo para su versión KumbiaPHP beta 2, mejorando y simplificando el desempeño 12 | del Scaffold para el Framework y que sin duda aporta a un gran avance en 13 | cualquier desarrollo de aplicación para usuarios iniciados en el uso de 14 | Kumbiaphp y usuarios avanzados, entregando para todos una gama alta de 15 | posibilidades. 16 | 17 | ## Concepto 18 | 19 | Scaffold es un método de meta-programación para construir aplicaciones de 20 | software que soportan bases de datos. Esta es una nueva técnica soportada por 21 | algunos frameworks del tipo MVC (Modelo-Vista-Controlador), donde el 22 | programador debe escribir una especificación que escriba como debe ser usada 23 | la aplicación de bases de datos. El compilador luego usara esta para generar 24 | un código que pueda usar la aplicación para leer, crear, actualizar y borrar 25 | entradas de la base de datos (algo conocido como CRUD o ABM), tratando de 26 | poner plantillas como un andamio Scaffold) en la cual construir una aplicación 27 | mas potente. 28 | 29 | Scaffolding es la evolución de códigos generadores de bases de datos desde 30 | ambientes más desarrollados, como ser CASE Generator de Oracle y otros tantos 31 | servidores 4GL para servicios al Cliente. Scaffolding se hizo popular gracias 32 | al framework "Ruby on Rails", que ha sido adaptado a otros frameworks, 33 | incluyendo Django, Monorail, KumbiaPHP framework entre otros. 34 | 35 | ## Objetivo 36 | 37 | Crear un CRUD 100% Funcional con tan solo 2 lineas de código en mi controller. 38 | 39 | KumbiaPHP toma como por arte de magia, los parámetros indicados en mi TABLA 40 | y arma todo el CRUD. 41 | 42 | ## Primeros Pasos 43 | 44 | Para realizar nuestro primer Scaffold, vamos a utilizar el mismo modelo que 45 | trabajamos en el [CRUD para KumbiaPHP Beta2](http://wiki.kumbiaphp.com/Beta2_CRUD_en_KumbiaPHP_Framework) , y que tiene por nombre menus. 46 | 47 | Modelo 48 | 49 | Crear el modelo, como de costumbre apuntando siempre a la clase ActiveRecord. 50 | 51 | [app]/models/menus.php: 52 | 53 | ```php 54 | controller/action/" title="My Link">My Link 87 | 88 | // Links an image located in public/img/image.jpg 89 | An Image 90 | 91 | // Links the CSS file in public/css/style.css 92 | 93 | ``` -------------------------------------------------------------------------------- /es/front-controller.md: -------------------------------------------------------------------------------- 1 | # Controlador Frontal 2 | 3 | Todas las peticiones web son manejadas por un solo Controlador Frontal (front 4 | controller), que es el punto de entrada único de toda la aplicación. 5 | 6 | Cuando el front controller recibe la petición, utiliza el sistema de 7 | enrutamiento de KumbiaPHP para asociar el nombre de un controlador y el de la 8 | acción mediante la URL escrita por el cliente (usuario u otra aplicación). 9 | 10 | Veamos la siguiente URL, esta llama al script index.php (que es el front 11 | controller) y sera entendido como llamada a una acción. 12 | 13 | http://localhost/kumbiaphp/micontroller/miaccion/ 14 | 15 | Debido a la reescritura de URL nunca se hace un llamado de forma explicita al 16 | index.php, solo se coloca el controlador, acción y parámetros. Internamente 17 | por las reglas reescritura de URL es llamado el front controller. Ver sección 18 | [¿Por qué es importante el Mod-Rewrite?](to-install.md#por-qu%C3%A9-es-importante-el-mod-rewrite) 19 | 20 | ## Destripando el Front Controller 21 | 22 | El front controller de KumbiaPHP se encarga de despachar las peticiones, lo 23 | que implica algo mas que detectar la acción que se ejecuta. De hecho, ejecuta 24 | el código común a todas las acciones, incluyendo: 25 | 26 | 1. Define las constantes del núcleo de la aplicación(APP_PATH, CORE_PATH y PUBLIC_PATH). 27 | 2. Carga e inicializa las clases del núcleo del framework (bootstrap). 28 | 3. Carga la configuración (Config). 29 | 4. Decodifica la URL de la petición para determinar la acción a ejecutar y los parámetros de la petición (Router). 30 | 5. Si la acción no existe, redirecciona a la acción del error 404 ( Router ). 31 | 6. Activa los filtros (por ejemplo, si la petición necesita autenticación) ( Router ). 32 | 7. Ejecuta los filtros, primera pasada (before). ( Router ) 33 | 8. Ejecuta la acción ( Router ). 34 | 9. Ejecuta los filtros, segunda pasada (after) ( Router ). 35 | 10. Ejecuta la vista y muestra la respuesta (View). 36 | 37 | A grande rasgos, este es el proceso del front controller, esto es todo lo que 38 | necesitas saber sobre este componente el cual es imprescindible de la 39 | arquitectura MVC dentro de KumbiaPHP 40 | 41 | ## Front Controller por defecto 42 | 43 | El front controller por defecto, llamado _index.php_ y ubicado en el directorio 44 | _public/_ del proyecto, es un simple script PHP.``` 45 | 46 | La definición de las constantes corresponde al primer paso descrito en la 47 | sección anterior. Después el controlador frontal incluye el bootstrap.php de 48 | la aplicación, que se ocupa de los pasos 2 a 5. Internamente el core de 49 | KumbiaPHP con sus componente Router y View ejecutan todos los pasos 50 | subsiguientes. 51 | 52 | Todas las constantes son valores por defecto de la instalación de KumbiaPHP en 53 | un ambiente local. 54 | 55 | ## Constantes de KumbiaPHP 56 | 57 | Cada constante cumple un objetivo específico con el fin de brindar mayor 58 | flexibilidad al momento de crear rutas (paths) en el framework. 59 | 60 | ### APP_PATH 61 | 62 | Constante que contiene la ruta absoluta al directorio donde se encuentra la 63 | aplicación (app), por ejemplo: 64 | 65 | ```php 66 | echo APP_PATH; 67 | //la salida es: /var/www/kumbiaphp/default/app/ 68 | ``` 69 | 70 | Con esta constante es posible utilizarla para incluir archivos que se 71 | encuentre bajo el árbol de directorio de la aplicación, por ejemplo si quiere 72 | incluir un archivo que esta en el directorio app/libs/test.php la forma de 73 | hacerlo seria. 74 | 75 | ```php 76 | include_once APP_PATH.'libs/test.php' ; 77 | ``` 78 | 79 | ### CORE_PATH 80 | 81 | Constante que contiene la ruta absoluta al directorio donde se encuentra el 82 | core de KumbiaPHP. por ejemplo: 83 | 84 | ```php 85 | echo CORE_PATH; 86 | //la salida es: /var/www/kumbiaphp/core/ 87 | ``` 88 | 89 | Para incluir archivos que se encuentre bajo este árbol de directorios, es el 90 | mismo procedimiento que se explicó para la constante APP_PATH. 91 | 92 | ### PUBLIC_PATH 93 | 94 | Constante que contiene la URL para el navegador (browser) y apunta al 95 | directorio *public/* para enlazar imágenes, CSS, JavaScript y todo lo que sea 96 | ruta para el navegador. 97 | 98 | ```php 99 | //Genera un link que ira al 100 | //controller: controller y action: action 101 | Mi Link 102 | 103 | //Enlaza una imagen que esta en public/img/imagen.jpg 104 | Una Imagen 105 | 106 | //Enlaza el archivo CSS en public/css/style.css 107 | 109 | ``` -------------------------------------------------------------------------------- /en/mvc.md: -------------------------------------------------------------------------------- 1 | # Model, View, Controller (MVC) 2 | 3 | ## What MVC is? 4 | 5 | In 1979, Trygve Reenskaug developed an architecture for creating interactive applications. In this design there are three components: models, views and controllers. The MVC model allows the separation of the application layers in interface, model and logic control. Programming in layers, is a style of programming where the primary goal is the separation of presentation design from the business logic. A basic example of this is separation of the data layer from the presentation layer (user interfase). 6 | 7 | The main advantage of this style is that development can be performed at various levels and in the event of any change only attacking the required level without having to review between mixed code. In addition, it allows to distribute the development of an application by levels so each work group is totally abstracted from the rest of levels. It is simply necessary to know the API (Application Interface) that exists between levels. The division into layers reduces complexity, facilitates the reuse and accelerates the process of assembling or disassembling any layer, or replace it by another (but with the same responsibility). 8 | 9 | In a Web application, a request is performed using HTTP and is sent to the controller. The controller may interact in many ways with the model, then the controller calls its view which obtains the state of the model that is sent from the controller and displays it to the user. 10 | 11 | ## How KumbiaPHP apply the MVC? 12 | 13 | KumbiaPHP Framework leverages the best patterns of oriented programming especially the Web pattern MVC (model, view, controller). The following describes the general operation of this paradigm in KumbiaPHP. 14 | 15 | The objective of this pattern is to make and maintain the separation between the logic of our application, data and presentation. This separation has some important advantages, as to be able to identify more easily in that layer is this causing a problem just know its nature. We can create various presentations without repeatedly typing the same application logic. Each part works independent and any changes centralize the effect over the others, so we can be sure that a change in one component does not affect the tasks in any part of the application. 16 | 17 | ## Additional information 18 | 19 | The basis of KumbiaPHP is the MVC and OOP, a traditional design pattern that works in three layers: 20 | 21 | - **Models:** They represent the information on which the application operates, its business logic. 22 | - **Views:** They displayed the model using Web pages and interacts with users (in principle). A view can be represented by any format output, we refer to xml, pdf, json, svg, png, etc. A simple view of a controller action has a phtml extension. all of this are seen. 23 | - **Controllers:** Respond to user actions (that is triggered in the views) and invoke changes in the views or models as needed. 24 | 25 | In KumbiaPHP controllers are separate parts, called front controller and a set of actions. Each action knows how to react to a particular type of request. 26 | 27 | The views are separated into templates, views and partials. 28 | 29 | The model provides a layer of abstraction from the database, in addition it gives functionality added to session and relational integrity validation data. This model helps to separate work in logic of business (models) and the presentation (view). 30 | 31 | For example, if you have an application that runs both on desktop computers and mobile devices then you could create two different views sharing the same actions on the controller and the logic of the model. The driver helps to hide the details of the protocol used in the request (HTTP, console mode, etc.) for the model and the view. 32 | 33 | Finally, the model abstracts the data logic, which makes independent views models. The implementation of this model is very light through small conventions can achieve much power and functionality. 34 | 35 | ## Case study (example of change) 36 | 37 | To better understand, here is an example of how an MVC architecture works to add to cart. First, the user interacts with the interface by selecting a product and pressing a button, this probably validates a form and sends a request to the server. 38 | 39 | 1. The Front Controller receives notification of a user action, and after running some tasks (routing, security, etc.), understands that it must run the action add on controller. 40 | 2. Action add access to the model and updates the object of the cart in the user session. 41 | 3. If the modification is stored correctly, the action prepares the content that will be returned in the response - confirmation of the addition and a complete list of products that are currently in your shopping cart. View joins the response of action in the body of the application to produce the shopping cart page. 42 | 4. It is finally transferred to the Web server that sends it to the user, who can read it and interact with it again. -------------------------------------------------------------------------------- /es/to-install.md: -------------------------------------------------------------------------------- 1 | # Instalar KumbiaPHP 2 | 3 | En esta sección se explican los pasos necesarios para poner en funcionamiento el framework en tu entorno de desarrollo. 4 | 5 | > ⚠️ **Advertencia** 6 | > 7 | > Esta instalación es un entorno de pruebas, pensado para experimentar con KumbiaPHP en un servidor local. No está 8 | > recomendada para el desarrollo de aplicaciones que vayan a ser publicadas en producción. 9 | 10 | ## Requisitos 11 | 12 | Como se mencionó anteriormente, KumbiaPHP es muy fácil de usar y, en ese sentido, los requisitos para hacerlo funcionar 13 | son mínimos, y solo es necesario un intérprete de [**PHP versión 8.0**](https://www.php.net/) o superior. 14 | 15 | ## Pasos para instalación 16 | 17 | 1. Descarga el archivo comprimido de KumbiaPHP desde la sección de descargas en 18 | [kumbiaphp.com](http://www.kumbiaphp.com/blog/manuales-y-descargas/) para obtener la versión más reciente del 19 | framework. 20 | 21 | Asegúrate de que el archivo tenga la extensión `.tgz` si usas Linux, o `.zip` si usas Windows, ya que de otro modo 22 | podría no descomprimirse correctamente. 23 | 24 | 2. Una vez descargado, descomprime su contenido en el directorio de tu preferencia. Para mantener la uniformidad en este 25 | manual, supondremos que el paquete ha sido descomprimido en un directorio llamado `kumbiaphp/`, con una estructura 26 | similar a la siguiente: 27 | 28 | ``` 29 | kumbiaphp/ 30 | ├── core/ 31 | ├── vendor/ 32 | └── default/ 33 | ├── app/ 34 | ├── public/ 35 | │ ├── .htaccess 36 | │ └── index.php 37 | ├── .htaccess 38 | └── index.php 39 | ``` 40 | 41 | 3. Abre una consola y navega hasta el directorio `default/app`: 42 | 43 | ```bash 44 | cd kumbiaphp/default/app 45 | ``` 46 | 47 | 4. Ejecuta el servidor de desarrollo incluido: 48 | 49 | ```bash 50 | ./bin/phpserver 51 | ``` 52 | 53 | Este comando inicia un servidor web local que utiliza el servidor embebido de PHP, facilitando así la ejecución 54 | inmediata de la aplicación sin necesidad de configuraciones adicionales. 55 | 56 | 5. Abre tu navegador web y accede a la siguiente dirección: 57 | 58 | ``` 59 | http://0.0.0.0:8001/ 60 | ``` 61 | 62 | o 63 | 64 | ``` 65 | http://127.0.0.1:8001/ 66 | ``` 67 | 68 | Si todo ha ido bien, deberías ver una página de bienvenida indicando que la instalación fue exitosa. 69 | 70 | ![Instalación exitosa](../images/successful-installation.jpg) 71 | 72 | > ℹ️ **Información** 73 | > 74 | > **Alternativa: Usar Apache o Nginx**, si lo prefieres, puedes utilizar un servidor web tradicional como Apache o Ngnix. Para ello, 75 | > consulta la sección dedicada a la [Instalación de KumbiaPHP en Servidores Web (Apache y Nginx)](installing-kumbiaphp-apache-nginx.md), donde encontrarás 76 | > instrucciones detalladas. 77 | 78 | ## Instalación con Composer 79 | 80 | Además de la instalación manual, también puedes instalar KumbiaPHP utilizando [**Composer**](https://getcomposer.org/), el administrador de dependencias estándar en PHP. Esta opción es más sencilla y mantiene el framework actualizado de manera automática. 81 | 82 | 1. Abre una consola en el directorio donde quieras crear tu proyecto y ejecuta: 83 | 84 | ```bash 85 | composer create-project kumbia/framework myapp 86 | ``` 87 | 88 | * `kumbia/framework` es el paquete oficial de KumbiaPHP en Composer. 89 | * `myapp` será el nombre de tu carpeta de proyecto. Puedes cambiarlo por el que prefieras. 90 | 91 | Composer descargará la última versión estable de KumbiaPHP junto con sus dependencias. 92 | 93 | 2. Accede al directorio del proyecto recién creado: 94 | 95 | ```bash 96 | cd myapp/default/app 97 | ``` 98 | 99 | 3. Inicia el servidor de desarrollo: 100 | 101 | ```bash 102 | ./bin/phpserver 103 | ``` 104 | 105 | Este comando levantará un servidor local con el puerto **8001** por defecto. 106 | 107 | 4. Abre tu navegador web y accede a: 108 | 109 | ``` 110 | http://127.0.0.1:8001/ 111 | ``` 112 | 113 | Si todo ha ido correctamente, deberías ver la página de bienvenida de KumbiaPHP confirmando que la instalación fue exitosa. 114 | 115 | ## Modos de una Aplicación 116 | 117 | KumbiaPHP ofrece dos modos de ejecución para una aplicación, definidos en el archivo 118 | [default/public/index.php](https://github.com/KumbiaPHP/KumbiaPHP/blob/master/default/public/index.php): 119 | 120 | ### Modo Desarrollo 121 | 122 | Este es el modo por defecto. La constante `PRODUCTION` está definida como `false`: 123 | 124 | ```php 125 | const PRODUCTION = false; 126 | ``` 127 | 128 | En este modo, la caché de KumbiaPHP está desactivada. Los cambios realizados en las tablas o campos de la base de datos, 129 | así como en las vistas, se reflejan de inmediato. 130 | 131 | ### Modo Producción 132 | 133 | Para activarlo, cambia la constante `PRODUCTION` a `true`: 134 | 135 | ```php 136 | const PRODUCTION = true; 137 | ``` 138 | 139 | En este modo, KumbiaPHP activa su sistema de caché, almacenando información clave como la metadata de la base de datos 140 | (nombres de tablas, campos, etc.) y las vistas que decidas cachear para mejorar el rendimiento. 141 | 142 | > ⚠️ **Advertencia** 143 | > 144 | > Cuando cambies `PRODUCTION` de `false` a `true`, debes eliminar manualmente el contenido del directorio de caché en 145 | `default/app/temp/cache/` para asegurar que la metadata sea renovada correctamente. Si no lo haces, podrías 146 | experimentar errores al guardar o mostrar información. 147 | -------------------------------------------------------------------------------- /en/console.md: -------------------------------------------------------------------------------- 1 | # The console 2 | 3 | ## Intro 4 | 5 | The console, is a tool for command line of KumbiaPHP, allowing to perform automated task in the scope of your app. In this way KumbiaPHP includes the following consoles: Cache, Model and Controller. 6 | 7 | Each console is composed of a set of commands, each command can receive sequences arguments and named arguments. To indicate a named argument is must use the prefix "\--" to the argument. 8 | 9 | ## How to use the console? 10 | 11 | For use of the console must be executed the dispatcher console of KumbiaPHP in a terminal, placed in the directory "app" of the application and execute the instruction according the following format: 12 | 13 | `php .../../core/console/kumbia.php [console] [command] [arg] [\--arg_name] = value` 14 | 15 | * * * 16 | 17 | If not specified the command to run, then run the console command "main". 18 | 19 | It is also possible to explicitly indicate the path to the app in the application directory using the named "path" argument. 20 | 21 | Examples: 22 | 23 | `php .../../core/console/kumbia.php cache clean --driver=sqlite` 24 | 25 | `php kumbia.php cache clean --driver=sqlite --path="/ var/www/app"` 26 | 27 | ## KumbiaPHP consoles 28 | 29 | ### Cache 30 | 31 | This console allows you to perform control over the cache of application. 32 | 33 | #### clean \[group\] \[--driver\] 34 | 35 | ### Allows you to clean the cache. 36 | 37 | ### Sequential arguments: 38 | 39 | - group: group name of cache items that will be deleted, if value is not specified, then clean all cache. 40 | 41 | ### Named arguments: 42 | 43 | - driver: driver cache corresponding to the cache cleaning (nixfile, file, sqlite, APC), if not specified, then the cache manager taken default. 44 | 45 | ### Example: 46 | 47 | ### php .../../core/console/kumbia.php cache clean 48 | 49 | * * * 50 | 51 | #### remove \[id\] \[group\] 52 | 53 | Removes an element from the cache. 54 | 55 | Sequential arguments: 56 | 57 | - id: id element in the cache. 58 | - group: name of group to which belongs the element, specifying no value, then use the 'default' group. 59 | 60 | Named arguments: 61 | 62 | - driver: driver cache corresponding to the cache cleaning (nixfile, file, sqlite, APC). 63 | 64 | Example: 65 | 66 | `php ../../core/console/kumbia.php cache remove viewclient my_views` 67 | 68 | * * * 69 | 70 | ### Model 71 | 72 | It allows you to manipulate the application models. 73 | 74 | #### create [model] 75 | 76 | Create a model using as a base the template located at "core/console/generators/model.php". 77 | 78 | Sequential arguments: 79 | 80 | - model: model name in smallcase. 81 | 82 | Example: 83 | 84 | `php ../../core/console/kumbia.php model create simple_auth` 85 | 86 | * * * 87 | 88 | #### delete [model] 89 | 90 | Delete a model. 91 | 92 | Sequential arguments: 93 | 94 | - model: model name in smallcase. 95 | 96 | Example: 97 | 98 | `php ../../core/console/kumbia.php model delete simple_auth` 99 | 100 | * * * 101 | 102 | ### Controller 103 | 104 | It allows you to manipulate the application controllers. 105 | 106 | #### create [controller] 107 | 108 | Create a controller using as a basis the located in the 'core/console/generators/controller.php' template. 109 | 110 | Sequential arguments: 111 | 112 | - controller: controller name in smallcase. 113 | 114 | Example: 115 | 116 | `php ../../core/console/kumbia.php controller create product_sales` 117 | 118 | * * * 119 | 120 | #### delete [controller] 121 | 122 | Delete controller. 123 | 124 | Sequential arguments: 125 | 126 | - controller: controller name in smallcase. 127 | 128 | Example: 129 | 130 | `php ../../core/console/kumbia.php controller delete product_sales` 131 | 132 | * * * 133 | 134 | # # 135 | 136 | ## Developing your consoles 137 | 138 | To develop your consoles you should consider the following: 139 | 140 | - Consoles that you develop for your application should be located in the directory "app/extensions/console". 141 | - The file should have the suffix "_console" as well as the class the "Console" suffix. 142 | - Each console command is equivalent to a class method. 143 | - Named arguments that are sent when you invoke a command are received in the first argument of the method corresponding to the command. 144 | - Sequential arguments, which are sent to invoke a command, are received as arguments to the invoked method subsequent to the first argument. 145 | - If he it is not specified the command to run, run by default the "main" method of the class. 146 | - Classes Load, Config and useful; they are loaded automatically to the console. 147 | - The constants APP_PATH, CORE_PATH and PRODUCTION; they are defined for the console environment. 148 | 149 | Example: 150 | 151 | Consider a part of the code, the cache console, whose functionality was explained in the previous section. 152 | 153 | & Lt;? Php 154 | 155 | Load :: lib ('cache'); 156 | 157 | Class CacheConsole 158 | 159 | { 160 | 161 | Public function clean ($ params, $ group = FALSE) 162 | 163 | { 164 | 165 | // get the cache driver 166 | 167 | If (isset ($ params ['driver'])) { 168 | 169 | $ Cache = Cache :: driver ($ params ['driver']); 170 | 171 | } Else { 172 | 173 | $ Cache = Cache :: driver () 174 | 175 | } 176 | 177 | // clear the cache 178 | 179 | If ($ cache-> clean ($ group)) { 180 | 181 | If ($ group) { 182 | 183 | Echo "-> The group $ group has been cleaned, PHP_EOL; 184 | 185 | } Else { 186 | 187 | Echo "-> The cache has been cleared", PHP_EOL; 188 | 189 | } 190 | 191 | } Else { 192 | 193 | Throw new KumbiaException ('Unable to delete content'); 194 | 195 | } 196 | 197 | } 198 | 199 | } 200 | 201 | 202 | 203 | ### Console::input 204 | 205 | This method of the Console class, allows you to read an input from the terminal, characterized by trying to read the entry until it is valid. 206 | 207 | `Console::input($message, $values = null)` 208 | 209 | $message (string): message to be displayed when this method requests an entry. 210 | 211 | $values (array): set of valid values for input. 212 | 213 | Example: 214 | 215 | `$answer = Console:input ('Continue?', array ('s ', 'n'));` 216 | 217 | * * * -------------------------------------------------------------------------------- /es/console.md: -------------------------------------------------------------------------------- 1 | 2 | # La Consola 3 | 4 | ## Introducción 5 | 6 | La consola, es una herramienta de línea de comandos de KumbiaPHP, que permite realizar tareas automatizadas en el ámbito de tu aplicación. En este sentido KumbiaPHP incluye las siguientes consolas: Cache, Model y Controller. 7 | 8 | Cada consola está compuesta por un conjunto de comandos, cada comando puede recibir argumentos secuenciales y argumentos con nombre . Para indicar un argumento con nombre se debe anteceder el prefijo " \--" al argumento. 9 | 10 | ## ¿Cómo utilizar la Consola? 11 | 12 | Para utilizar la consola debes ejecutar el despachador de comandos de consola de KumbiaPHP en un terminal, ubicarte en el directorio " app" de tu aplicación y ejecutar la instrucción acorde al siguiente formato: 13 | 14 | `php ../../core/console/kumbia.php [ consola ] [ comando ] [ arg ] [ \--arg_nom 15 | ] =valor` 16 | 17 | --- 18 | 19 | Si no se especifica el comando a ejecutar, entonces se ejecutará el comando "main " de la consola. 20 | 21 | También es posible indicar la ruta al directorio app de la aplicación explícitamente por medio del argumento con nombre " path ". 22 | 23 | Ejemplos: 24 | 25 | `php ../../core/console/kumbia.php cache clean --driver=sqlite` 26 | 27 | `php kumbia.php cache clean --driver=sqlite --path="/var/www/app"` 28 | 29 | ## Consolas de KumbiaPHP 30 | 31 | ### Cache 32 | 33 | Esta consola permite realizar tareas de control sobre la cache de aplicación. 34 | 35 | #### clean [group] [--driver] 36 | 37 | ### Permite limpiar la cache. 38 | 39 | ### Argumentos secuenciales: 40 | 41 | * group: nombre de grupo de elementos de cache que se eliminará, si no se especifica valor, entonces se limpiará toda la cache. 42 | 43 | ### Argumentos con nombre: 44 | 45 | * driver: manejador de cache correspondiente a la cache a limpiar (nixfile, file, sqlite, APC), si no se especifica, entonces se toma el manejador de cache predeterminado. 46 | 47 | ### Ejemplo: 48 | 49 | ### php ../../core/console/kumbia.php cache clean 50 | 51 | --- 52 | 53 | #### remove [id] [group] 54 | 55 | Elimina un elemento de la cache. 56 | 57 | Argumentos secuenciales: 58 | 59 | * id: id de elemento en cache. 60 | * group: nombre de grupo al que pertenece el elemento, si no se especifica valor, entonces se utilizará el grupo 'default'. 61 | 62 | Argumentos con nombre: 63 | 64 | * driver: manejador de cache correspondiente a la cache a limpiar (nixfile, file, sqlite, APC). 65 | 66 | Ejemplo: 67 | 68 | `php ../../core/console/kumbia.php cache remove vista1 mis_vistas` 69 | 70 | --- 71 | 72 | ### Model 73 | 74 | Permite manipular modelos de la aplicación. 75 | 76 | #### create [model] 77 | 78 | Crea un modelo utilizando como base la plantilla ubicada en 79 | "core/console/generators/model.php". 80 | 81 | Argumentos secuenciales: 82 | 83 | * model: nombre de modelo en smallcase. 84 | 85 | Ejemplo: 86 | 87 | `php ../../core/console/kumbia.php model create venta_vehiculo` 88 | 89 | --- 90 | 91 | #### delete [model] 92 | 93 | Elimina un modelo. 94 | 95 | Argumentos secuenciales: 96 | 97 | * model: nombre de modelo en smallcase. 98 | 99 | Ejemplo: 100 | 101 | `php ../../core/console/kumbia.php model delete venta_vehiculo` 102 | 103 | --- 104 | 105 | ### Controller 106 | 107 | Permite manipular controladores de la aplicación. 108 | 109 | #### create [controller] 110 | 111 | Crea un controlador utilizando como base la plantilla ubicada en 'core/console/generators/controller.php'. 112 | 113 | Argumentos secuenciales: 114 | 115 | * controller: nombre de controlador en smallcase. 116 | 117 | Ejemplo: 118 | 119 | `php ../../core/console/kumbia.php controller create venta_vehiculo` 120 | 121 | --- 122 | 123 | #### delete [controller] 124 | 125 | Elimina un controlador. 126 | 127 | Argumentos secuenciales: 128 | 129 | * controller: nombre de controlador en smallcase. 130 | 131 | Ejemplo: 132 | 133 | `php ../../core/console/kumbia.php controller delete venta_vehiculo` 134 | 135 | --- 136 | 137 | ## 138 | 139 | ## Desarrollando tus Consolas 140 | 141 | Para desarrollar tus consolas debes de considerar lo siguiente: 142 | 143 | * Las consolas que desarrolles para tu aplicación deben estar ubicadas en el directorio "app/extensions/console". 144 | * El archivo debe tener el sufijo "_console" y de igual manera la clase el sufijo "Console". 145 | * Cada comando de la consola equivale a un método de la clase. 146 | * Los argumentos con nombre que son enviados al invocar un comando se reciben en el primer argumento del método correspondiente al comando. 147 | * Los argumentos secuenciales, que son enviados al invocar un comando, se reciben como argumentos del método invocado posteriores al primer argumento. 148 | * Si no se especifica el comando a ejecutar, se ejecutará de manera predeterminada el método "main" de la clase. 149 | * Las clases Load, Config y Util; son cargadas automáticamente para la consola. 150 | * Las constantes APP_PATH, CORE_PATH y PRODUCTION; se encuentran definidas para el entorno de la consola. 151 | 152 | Ejemplo: 153 | 154 | Consideremos una parte del código, de la consola cache, cuya funcionalidad fue explicada en la sección anterior. 155 | 156 | ``` 157 | clean($group)) { 184 | 185 | if ($group) { 186 | 187 | echo "-> Se ha limpiado el grupo $group", PHP_EOL; 188 | 189 | } else { 190 | 191 | echo "-> Se ha limpiado la cache", PHP_EOL; 192 | 193 | } 194 | 195 | } else { 196 | 197 | throw new KumbiaException('No se ha logrado eliminar el contenido'); 198 | 199 | } 200 | 201 | } 202 | 203 | } 204 | 205 | ``` 206 | 207 | ### Console::input 208 | 209 | Este método de la clase Console, permite leer una entrada desde el terminal, se caracteriza por intentar leer la entrada hasta que esta sea válida. 210 | 211 | `Console::input($message, $values = null)` 212 | 213 | $message (string): mensaje a mostrar al momento de solicitar la entrada. 214 | 215 | $values (array): conjunto de valores válidos para la entrada. 216 | 217 | Ejemplo: 218 | 219 | `$valor = Console::input('¿Desea continuar?', array('s', 'n'));` 220 | 221 | --- 222 | -------------------------------------------------------------------------------- /en/crud.md: -------------------------------------------------------------------------------- 1 | # CRUD 2 | 3 | ## Introduction 4 | 5 | This example allows easy understanding of the implementation of a CRUD (Create, Read, Update and Delete) without the need of a Scaffold, doing a correct handling of the MVC in KumbiaPHP. 6 | 7 | ## Configuring database.ini 8 | 9 | Configure the databases.ini with the data and the db engine to be used. 10 | 11 | ## Model 12 | 13 | Create the Model that defines the table in the database, for complementing the example we create the follow table. 14 | 15 | ```sql 16 | CREATE TABLE menus 17 | ( 18 | id int unique not null auto_increment, 19 | nombre varchar(100), 20 | titulo varchar(100) not null, 21 | primary key(id) 22 | ) 23 | ``` 24 | 25 | We will now define the model which allows us to interact with the database. 26 | 27 | [app]/models/menus.php: 28 | 29 | ```php 30 | paginate("page: $page", "per_page: $ppage", 'order: id desc'); 43 | } 44 | } 45 | 46 | ``` 47 | 48 | ## Controller 49 | 50 | The controller handles client requests and replies (ie, a browser). In this controller we must define all the CRUD actions/functions we need. 51 | 52 | [app]/controllers/menus_controller.php: 53 | 54 | ```php 55 | listMenus = (new Menus)->getMenus($page); 71 | } 72 | 73 | /** 74 | * Make a record 75 | */ 76 | public function create() 77 | { 78 | /** 79 | * Verify if the user send the form(submit) and if also 80 | * inner of array POST exist a variable called "menus" 81 | * that which applies for the auto load of object for save the 82 | * date send for POST using auto load of object 83 | */ 84 | if (Input::hasPost('menus')) { 85 | /** 86 | * the data of form is sent to model for construct and ActiveRecord collect 87 | * this data and associate to the corresponding field when it's use the convention 88 | * model.field 89 | */ 90 | $menu = new Menus(Input::post('menus')); 91 | //In case that the operation fail 92 | if ($menu->create()) { 93 | Flash::valid('Success'); 94 | //Delete the POST, if don't wanna that it can be seen in the form 95 | Input::delete(); 96 | return; 97 | } 98 | 99 | Flash::error('Operation Fail'); 100 | } 101 | } 102 | 103 | /** 104 | * Edit a record 105 | * 106 | * @param int $id (required) 107 | */ 108 | public function edit($id) 109 | { 110 | $menu = new Menus(); 111 | 112 | //verify if the post as send data (submit) 113 | if (Input::hasPost('menus')) { 114 | 115 | if ($menu->update(Input::post('menus'))) { 116 | Flash::valid(Success'); 117 | //redirect por default to the index of controller 118 | return Redirect::to(); 119 | } 120 | Flash::error('Operation Fail'); 121 | return; 122 | } 123 | 124 | //Applied the auto load of object, for start the edition 125 | $this->menus = $menu->find_by_id((int) $id); 126 | 127 | } 128 | 129 | /** 130 | * Delete a menu 131 | * 132 | * @param int $id (require) 133 | */ 134 | public function del($id) 135 | { 136 | if ((new Menus)->delete((int) $id)) { 137 | Flash::valid('Success'); 138 | } else { 139 | Flash::error('Operation fail'); 140 | } 141 | 142 | //redirect to the index of controller 143 | return Redirect::to(); 144 | } 145 | } 146 | 147 | ``` 148 | 149 | ## Views 150 | 151 | We add the views... 152 | 153 | [app]/views/menus/index.phtml 154 | 155 | ```php 156 |
157 | 158 |

Menus

159 | 168 | 169 | // Manual paginate example, exist partials ready in formats digg, clasic,... 170 | prev) echo Html::linkAction("index/$listMenus->prev/", '<< Previous |') ?> 171 | next) echo Html::linkAction("index/$listMenus->next/", 'Next >>') ?> 172 |
173 | ``` 174 | 175 | [app]/views/menus/create.phtml 176 | 177 | ```php 178 | 179 |

Create menu

180 | 181 | 182 | 183 | 185 | 186 | 188 | 189 | 190 | 191 | 192 | ``` 193 | 194 | [app]/views/menus/edit.phtml 195 | 196 | ```php 197 | 198 |

Edit menu

199 | 200 | 201 | 202 | 203 | 204 | 205 | ``` 206 | 207 | ## Testing the CRUD 208 | 209 | Now it only remains to try all the code that we have generated, at this point it is important to know the behavior of the [URL's in KumbiaPHP](http://wiki.kumbiaphp.com/Hola_Mundo_KumbiaPHP_Framework#KumbiaPHP_URLS). 210 | 211 | - index is the default action (ie, http://domain/menus/index/). Declaration of /index it's optional, because the controller would autoload /index if no other has been specified (ie, http://domain/menus/) 212 | - Create creates a menu in the database http://localhost/menus/create/ 213 | - Edit and Delete actions are handled from the index in this example, because receives the data/ids to operate from the index. -------------------------------------------------------------------------------- /en/preface.md: -------------------------------------------------------------------------------- 1 | # Preface 2 | 3 | ## Acknowledgments 4 | This manual is dedicated to everyone who, through their time and support (whether large or small), has helped this 5 | framework improve day by day. To the entire KumbiaPHP community, with their questions, bug reports, contributions, and 6 | critiques—thank you all! 7 | 8 | ## About This Manual 9 | The KumbiaPHP book aims to demonstrate how this framework can assist in a developer's daily work. It shows different 10 | aspects of KumbiaPHP and explains why it might be the tool you have been waiting for to begin your project. It is under 11 | continuous development (graphic design, spelling and grammar review, content updates, etc.), just like the framework 12 | itself, so it is recommended to always use the latest version. 13 | 14 | This manual’s current edition has undergone significant changes compared to the previous one. Thanks to community 15 | feedback, recurring questions were identified in the group, the forum, and the chat. In addition, improper use of the 16 | MVC pattern and underutilization of Object-Oriented Programming (OOP) capabilities were detected. This edition strives 17 | to address these aspects and improve usage clarity, allowing for the creation of more maintainable, higher-quality 18 | applications. 19 | 20 | ## About KumbiaPHP 21 | KumbiaPHP is a Latin product made for the world. Programming should be as enjoyable as dancing, and KumbiaPHP makes 22 | coding as pleasant as dancing. It is a free-to-use framework under the New BSD license, so you can use it in your 23 | projects as long as you respect the terms of that license. It is recommended to always use stable and recent versions, 24 | as they include fixes, new features, and notable improvements. 25 | 26 | ## About the Community 27 | The KumbiaPHP community originally emerged from Spanish-speaking developers, giving rise to a framework that was 28 | entirely in Spanish. However, there is now an English-speaking community as well, contributing to KumbiaPHP’s 29 | international expansion. Over time, various communication channels have been implemented, including a mailing list, a 30 | forum, an IRC channel, a Wiki, and most recently, a Slack workspace, which is the most convenient way to get support and 31 | interact with other users. This collaborative effort makes the community essential for enhancing and improving KumbiaPHP. 32 | For more information, visit the [Official KumbiaPHP Website](https://www.kumbiaphp.com). 33 | 34 | ## Why Use KumbiaPHP Framework? 35 | Many people ask questions such as: how does this framework work, is it just another one, is it easy, how powerful is it, 36 | and so on. Below are some reasons to use KumbiaPHP: 37 | 38 | - It is very easy to use (Zero-Config). Starting with KumbiaPHP is extremely simple: just decompress it and begin 39 | working. This philosophy is also known as “Convention over Configuration.” 40 | - It speeds up development. Creating a very functional application with KumbiaPHP can take only minutes or hours, 41 | allowing you to satisfy client needs without using excessive time. With its numerous tools, you can accomplish more in 42 | less time. 43 | - It separates business logic from presentation. One of the best web development practices is to separate data logic 44 | from presentation. With KumbiaPHP, implementing the MVC (Model, View, Controller) pattern is straightforward, which 45 | makes applications easier to maintain and scale. 46 | - It reduces the use of other languages. Thanks to Helpers and patterns like ActiveRecord, it minimizes the need to 47 | write HTML and SQL (even if only to a lesser extent). KumbiaPHP handles these tasks, resulting in clearer, more 48 | natural code that is less prone to errors. 49 | - It speaks English (and also Spanish, with more languages to come)! 50 | KumbiaPHP originally offered documentation, error messages, and configuration files in Spanish, but an 51 | internationalization (i18n) system is gradually being introduced to provide multilingual support and reach an even 52 | broader global audience. 53 | - Its learning curve is very short, especially for those who already have experience with Object-Oriented Programming. 54 | - It feels like a game. Without realizing it, you apply multiple design patterns that simplify work by providing 55 | abstraction, reducing code, and making the application easier to understand. Working with KumbiaPHP means naturally 56 | applying many patterns. 57 | - It is Free Software. There is no need to worry about extra licensing, and KumbiaPHP encourages learning communities, 58 | where knowledge is shared by everyone, and each person decides how best to use it. 59 | - It enables the creation of robust applications. Today’s applications require solid architectures. KumbiaPHP provides 60 | an architecture that is easy to learn and implement, without overcomplicating concepts or sacrificing quality. 61 | 62 | ## What Does KumbiaPHP Provide? 63 | KumbiaPHP is an effort to produce a framework that reduces the time needed to develop a web application without 64 | negatively affecting programmers, based on key principles we always keep in mind: 65 | 66 | - KISS (“Keep It Simple, Stupid”). 67 | - DRY (“Don’t Repeat Yourself,” also known as “Once and Only Once”). 68 | - Convention over Configuration. 69 | - Speed. 70 | 71 | In addition, KumbiaPHP is based on the following premises: 72 | 73 | - Easy to learn. 74 | - Easy to install and configure. 75 | - Compatible with many platforms. 76 | - Ready for commercial applications. 77 | - Simple in most cases but flexible enough for more complex scenarios. 78 | - Support for numerous features in modern web applications. 79 | - Application of productive and efficient programming practices and patterns. 80 | - Creation of applications that are easy to maintain. 81 | - Based on Free Software. 82 | 83 | The main goal is to create applications that are practical for the end user and not just for the programmer. Most tasks 84 | that consume the developer’s time should be automated by KumbiaPHP, allowing focus on the application’s business logic. 85 | You should not have to reinvent the wheel every time you start a new software project. 86 | 87 | To achieve these objectives, KumbiaPHP is written in PHP5 (fully compatible with PHP 8.0) and has been tested in 88 | real-world applications spanning various sectors with different demands and functionalities. It is compatible with the 89 | most commonly used databases today: 90 | 91 | - MySQL 92 | - PostgreSQL 93 | - Oracle 94 | - SQLite 95 | 96 | KumbiaPHP’s object model is applied in the following layers: 97 | 98 | - [Application Logic](model.md) 99 | - [Database Abstraction and Object-Relational Mapping](active-record.md) 100 | 101 | Common features of web applications that KumbiaPHP automates include: 102 | 103 | - Templates (TemplateView). 104 | - Form validation and persistence. 105 | - Cache management. 106 | - Scaffolding. 107 | - Front Controller. 108 | - AJAX interaction. 109 | - Form generation. 110 | - Security. 111 | -------------------------------------------------------------------------------- /en/configuration.md: -------------------------------------------------------------------------------- 1 | ## Configuration: `config/config.php` File 2 | 3 | The `default/app/config/config.php` file is a central configuration component for any KumbiaPHP application. Through 4 | this file, you can customize key settings of the application, including its name, database, date format, debugging, and 5 | more. 6 | 7 | In the `config.php` file, all options are organized under the 'application' index. This allows application 8 | configurations to be easily accessible and modifiable in one place. Additionally, it is possible to add more indexes to 9 | define additional settings or include specific configuration files. This provides flexibility to manage different aspects of the project and fully customize the application according to the developer's needs. 10 | 11 | ```php 12 | [ 19 | 'name' => 'KUMBIAPHP PROJECT', 20 | 'database' => 'development', 21 | 'dbdate' => 'YYYY-MM-DD', 22 | 'debug' => 'On', 23 | 'log_exceptions' => 'On', 24 | //'cache_template' => 'On', 25 | 'cache_driver' => 'file', 26 | 'metadata_lifetime' => '+1 year', 27 | 'namespace_auth' => 'default', 28 | //'routes' => '1', 29 | ], 30 | ]; 31 | 32 | ``` 33 | 34 | Here is a detailed explanation of each parameter. 35 | 36 | ### Application Name 37 | 38 | The application name, represented by the `name` parameter, identifies the project in the KumbiaPHP environment. Although 39 | it does not directly affect functionality, it is used to differentiate and personalize the project. 40 | 41 | ### Database 42 | 43 | The `database` parameter determines which database configuration should be used for the application. This value must 44 | match one of the identifiers in the `databases.php` file, such as "development" or "production". This allows easy 45 | switching between different environments. 46 | 47 | ### Date Format 48 | 49 | The `dbdate` parameter specifies the default date format for the application, using the standard notation `YYYY-MM-DD`. 50 | This setting ensures that all dates in the application are consistent. 51 | 52 | ### Debugging 53 | 54 | The `debug` option turns the display of errors on or off. In "On" mode, errors are shown to help in the development 55 | process. In production, it should be turned off ("Off") to avoid exposing errors to end users. 56 | 57 | ### Exception Logging 58 | 59 | The `log_exceptions` parameter determines whether captured exceptions are displayed on the screen. This can be useful 60 | for tracking issues during development but should be turned off in production to avoid revealing sensitive information. 61 | 62 | ### Template Caching 63 | 64 | The `cache_template` parameter can be enabled to cache templates, improving performance by reducing the need to 65 | recompile them. 66 | 67 | ### Cache Driver 68 | 69 | The `cache_driver` option allows selecting the caching mechanism to use. Available options include: 70 | - **file**: Files on the storage system. 71 | - **sqlite**: An SQLite database. 72 | - **memsqlite**: An in-memory SQLite database. 73 | 74 | ### Metadata Lifetime 75 | 76 | The `metadata_lifetime` parameter defines how long cached metadata should be considered valid. Any format compatible 77 | with the `strtotime()` function, such as "+1 year," is accepted. 78 | 79 | ### Authentication Namespace 80 | 81 | The `namespace_auth` allows defining a default namespace for the authentication system, facilitating the management of 82 | multiple namespaces according to the application's context. 83 | 84 | ### Custom Routes 85 | 86 | The `routes` parameter can be enabled to allow custom routes through the `routes.php` file. This offers flexibility in 87 | reorganizing the URL structure in the application. 88 | 89 | ### General Considerations 90 | 91 | When configuring this file, it is crucial to ensure that parameters such as `debug` and `log_exceptions` are disabled in 92 | production environments to maintain security. Additionally, choosing the appropriate caching mechanism and date format 93 | can significantly improve the application's performance and consistency. 94 | 95 | ## Configuration: `config/exception.php` File (v 1.2) 96 | 97 | The `config/exception.php` file in KumbiaPHP allows configuring the IP addresses from which exception details will be 98 | displayed instead of a generic 404 error. This functionality is especially useful during the development phase, where 99 | developers need to see error traces and specific details to debug effectively. This feature is available from version 100 | 1.2.0 onwards. 101 | 102 | ### File Location 103 | 104 | The configuration file is located at `default/app/config/exception.php`. 105 | 106 | ### File Content 107 | 108 | The file is in PHP array format and contains a single key `trustedIp`, which is an array of IP addresses. Below is the 109 | default content of the file: 110 | 111 | ```php 112 | [] 118 | ]; 119 | ``` 120 | 121 | ### Trusted IPs Configuration 122 | 123 | The `trustedIp` array should be configured with the IP addresses from which the full details of exceptions will be 124 | displayed. This is useful when you want to allow certain developers or development teams to access this information from 125 | specific locations. 126 | 127 | **Example:** 128 | ```php 129 | ['192.168.1.100', '203.0.113.5'] 134 | ]; 135 | ``` 136 | In this example, exception details will be shown only to users accessing from the IPs `192.168.1.100` and `203.0.113.5`. 137 | 138 | ### Default Behavior 139 | 140 | By default, the `trustedIp` array is empty. This means that unless configured, exception details will only be shown in 141 | the localhost environment. If left empty, only connections from `127.0.0.1` or `::1` (localhost in IPv6) will see the 142 | full details of exceptions. 143 | 144 | ### Importance of Configuration 145 | 146 | This configuration is crucial for maintaining security in production environments. Showing exception details to 147 | unauthorized users can expose sensitive information and potential vulnerabilities. Therefore, it is recommended to keep 148 | this list restricted to trusted IPs and use it with care. 149 | 150 | ### Additional Considerations 151 | - **Security:** Ensure that only trusted IP addresses are added to avoid potential information leaks. 152 | - **Production Environment:** In a production environment, it is advisable to disable the display of exception details 153 | for all users or strictly restrict it to internal IP addresses. 154 | - **Maintenance:** Regularly review and update the IP list in `trustedIp` to reflect changes in the infrastructure or 155 | development team. 156 | 157 | With this configuration, KumbiaPHP allows flexible and secure handling of exception debugging, adapting to the specific 158 | needs of each development and production environment. -------------------------------------------------------------------------------- /en/installing-kumbiaphp-apache-nginx.md: -------------------------------------------------------------------------------- 1 | # Installing KumbiaPHP on Web Servers (Apache and Nginx) for GNU/Linux (Debian, Ubuntu and derivatives) 2 | 3 | This section provides instructions for installing and configuring KumbiaPHP using **Apache** or **Nginx** as a web 4 | server on Linux distributions such as Ubuntu and Debian. By the end, you will have a functional KumbiaPHP installation 5 | ready for development. 6 | 7 | > ⚠️ **Warning** 8 | > 9 | > This installation is intended as a testing environment, designed for experimenting with KumbiaPHP on a local server. 10 | > It is **not** recommended for developing applications that will be deployed to production. 11 | 12 | ## Prerequisites 13 | 14 | * A **Web Server** (Apache HTTP or Nginx) installed and running. 15 | * **PHP 8.0** (or later) with required extensions: `php-mbstring`, `php-xml`, `php-json`, etc. 16 | * Basic knowledge of terminal commands (`sudo`, moving files, etc.). 17 | 18 | ## Download and Extract KumbiaPHP 19 | 20 | 1. Go to the directory where the project files will be stored, e.g. `/var/www`: 21 | 22 | ```bash 23 | cd /var/www 24 | ``` 25 | 26 | 2. **Download** the latest `.tar.gz` file from the official repository: 27 | 28 | ```bash 29 | wget https://github.com/KumbiaPHP/KumbiaPHP/archive/v1.2.1.tar.gz 30 | ``` 31 | 32 | 3. **Extract** the contents: 33 | 34 | ```bash 35 | tar -xzvf v1.2.1.tar.gz 36 | ``` 37 | 38 | 4. (Optional) **Rename** the resulting folder: 39 | 40 | ```bash 41 | mv KumbiaPHP-1.2.1 kumbiafw 42 | ``` 43 | 44 | ## Server-Specific Configuration 45 | 46 | ### Apache 47 | 48 | 1. Create a new configuration file in `/etc/apache2/sites-available/`, for example `kumbiafw.conf`: 49 | 50 | ```apache 51 | 52 | ServerName kumbia.fw 53 | DocumentRoot /var/www/kumbiafw/default/public 54 | 55 | 56 | AllowOverride All 57 | Require all granted 58 | 59 | 60 | ErrorLog ${APACHE_LOG_DIR}/kumbiafw-error.log 61 | CustomLog ${APACHE_LOG_DIR}/kumbiafw-access.log combined 62 | 63 | ``` 64 | 65 | * Replace `kumbia.fw` with the local domain or hostname you want to use. 66 | * Adjust the `DocumentRoot` path to match where you extracted KumbiaPHP. 67 | 68 | 2. Enable the new site and the `rewrite` module: 69 | 70 | ```bash 71 | sudo a2ensite kumbiafw.conf 72 | sudo a2enmod rewrite 73 | sudo systemctl reload apache2 74 | ``` 75 | 76 | #### Why is `mod_rewrite` important? 77 | 78 | `mod_rewrite` is an Apache module that allows rewriting user-friendly URLs. 79 | KumbiaPHP leverages this feature to let you use clean, readable URLs, like those seen in modern applications (without 80 | symbols such as `?`, `&`, or file extensions like `.php`, `.asp`, `.aspx`, etc.). 81 | 82 | Additionally, `mod_rewrite` enhances application security by restricting direct access to internal directories and 83 | files. Only the contents of the `public/` directory are accessible, ensuring business logic and core classes remain 84 | protected. 85 | 86 | It also improves search engine indexing, which benefits the visibility of your applications. 87 | 88 | ### Nginx 89 | 90 | 1. Create a new server block in `/etc/nginx/sites-available/kumbiafw`: 91 | 92 | **Using `$_SERVER['PATH_INFO']`:** 93 | 94 | ```nginx 95 | server { 96 | listen 80; 97 | server_name kumbia.fw; 98 | root /var/www/kumbiafw/default/public; 99 | index index.php index.html index.htm; 100 | 101 | location / { 102 | try_files $uri $uri/ /index.php$uri?$args; 103 | } 104 | 105 | location ~ \.php { 106 | # Extract PATH_INFO after index.php 107 | fastcgi_split_path_info ^(.+\.php)(/.*)$; 108 | 109 | fastcgi_pass 127.0.0.1:9000; 110 | # fastcgi_pass unix:/run/php/php-fpm.sock; 111 | 112 | include fastcgi_params; 113 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 114 | fastcgi_param PATH_INFO $fastcgi_path_info; 115 | } 116 | 117 | location ~ /\.ht { 118 | deny all; 119 | } 120 | } 121 | ``` 122 | 123 | **Using `$_GET['_url']`:** 124 | 125 | ```nginx 126 | server { 127 | listen 80; 128 | server_name kumbia.fw; 129 | root /var/www/kumbiafw/default/public; 130 | index index.php index.html index.htm; 131 | 132 | location / { 133 | try_files $uri $uri/ /index.php?_url=$uri&$args; 134 | } 135 | 136 | location ~ \.php { 137 | fastcgi_pass 127.0.0.1:9000; 138 | # fastcgi_pass unix:/run/php/php-fpm.sock; 139 | 140 | include fastcgi_params; 141 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 142 | } 143 | 144 | location ~ /\.ht { 145 | deny all; 146 | } 147 | } 148 | ``` 149 | 150 | * Update `server_name` and `root` as needed. 151 | * Make sure the PHP-FPM socket corresponds to your PHP version. 152 | 153 | > ℹ️ **Important** 154 | > If you are using another PHP version (e.g. 8.1), adjust the socket path in Nginx (`fastcgi_pass`) or the corresponding 155 | > module in Apache. Some instructions may vary slightly depending on your Ubuntu or Debian version. 156 | 157 | 2. Enable the new site: 158 | 159 | ```bash 160 | sudo ln -s /etc/nginx/sites-available/kumbiafw /etc/nginx/sites-enabled/ 161 | sudo nginx -t 162 | sudo systemctl reload nginx 163 | ``` 164 | 165 | ## Set Permissions 166 | 167 | Ensure that the web server user (usually `www-data`) has access to the files: 168 | 169 | ```bash 170 | sudo chown -R www-data:www-data /var/www/kumbiafw 171 | sudo find /var/www/kumbiafw -type d -exec chmod 755 {} \; 172 | sudo find /var/www/kumbiafw -type f -exec chmod 644 {} \; 173 | ``` 174 | 175 | * Directories should have `755` permissions. 176 | * Files should have `644` permissions. 177 | 178 | ## Test the Installation 179 | 180 | 1. Edit your `/etc/hosts` file to map the server name: 181 | 182 | ```bash 183 | sudo nano /etc/hosts 184 | ``` 185 | 186 | Add this line: 187 | 188 | ``` 189 | 127.0.0.1 kumbia.fw 190 | ``` 191 | 192 | 2. Open your browser and visit `http://kumbia.fw`. You should see the KumbiaPHP welcome page. 193 | 194 | ![Successful installation](../images/welcome-page.jpg) 195 | 196 | ## Verification with a Controller and View 197 | 198 | 1. Create a file `app/controllers/test_controller.php`: 199 | 200 | ```php 201 | date = date('Y-m-d H:i:s'); 217 | } 218 | } 219 | ``` 220 | 221 | 2. And its corresponding view in `app/views/test/index.phtml`: 222 | 223 | ```php 224 |

Welcome to KumbiaPHP!

225 | Today's date and time is: 226 | ``` 227 | 228 | 3. Visit `http://kumbia.fw/test` in your browser to see the welcome message. 229 | 230 | ![Welcome message](../images/test-welcome-message.jpg) 231 | -------------------------------------------------------------------------------- /es/crud.md: -------------------------------------------------------------------------------- 1 | # CRUD 2 | 3 | ## Introducción 4 | 5 | Este ejemplo, permite de manera sencilla conocer y entender la 6 | implementación de un CRUD (Create, Read, Update y Delete en inglés) sin la 7 | necesidad de un Scaffold y un manejo correcto del MVC en KumbiaPHP. 8 | 9 | ## Configuración de conexión a la base de datos 10 | 11 | Configurar el archivo [databases.ini o databases.php](active-record.md#configurando-conexión-a-la-base-de-datos) , 12 | con los datos y motor de base de datos a utilizar. 13 | 14 | ## Modelo 15 | 16 | Crear el Modelo dado por la definición de una tabla en la BD, 17 | para efecto del ejemplo creamos la siguiente tabla. 18 | 19 | ```sql 20 | CREATE TABLE menus 21 | ( 22 | id int unique not null auto_increment, 23 | nombre varchar(100), 24 | titulo varchar(100) not null, 25 | primary key(id) 26 | ) 27 | ``` 28 | 29 | Vamos ahora a definir el modelo el cual nos permite interactuar con la BD. 30 | 31 | [app]/models/menus.php: 32 | 33 | ```php 34 | paginate("page: $page", "per_page: $ppage", 'order: id desc'); 47 | } 48 | } 49 | 50 | ``` 51 | 52 | ## Controller 53 | 54 | El controlador es encargado de atender las peticiones del cliente (ej. 55 | browser) y a su vez de darle una respuesta. En este controller vamos a definir 56 | todas las operaciones CRUD que necesitamos. 57 | 58 | [app]/controllers/menus_controller.php: 59 | 60 | ```php 61 | listMenus = (new Menus)->getMenus($page); 77 | } 78 | 79 | /** 80 | * Crea un Registro 81 | */ 82 | public function create() 83 | { 84 | /** 85 | * Se verifica si el usuario envío el form (submit) y si además 86 | * dentro del array POST existe uno llamado "menus" 87 | * el cual aplica la autocarga de objeto para guardar los 88 | * datos enviado por POST utilizando autocarga de objeto 89 | */ 90 | if (Input::hasPost('menus')) { 91 | /** 92 | * se le pasa al modelo por constructor los datos del form y ActiveRecord recoge esos datos 93 | * y los asocia al campo correspondiente siempre y cuando se utilice la convención 94 | * model.campo 95 | */ 96 | $menu = new Menus(Input::post('menus')); 97 | //En caso que falle la operación de guardar 98 | if ($menu->create()) { 99 | Flash::valid('Operación exitosa'); 100 | //Eliminamos el POST, si no queremos que se vean en el form 101 | Input::delete(); 102 | return; 103 | } 104 | 105 | Flash::error('Falló Operación'); 106 | } 107 | } 108 | 109 | /** 110 | * Edita un Registro 111 | * 112 | * @param int $id (requerido) 113 | */ 114 | public function edit($id) 115 | { 116 | $menu = new Menus(); 117 | 118 | //se verifica si se ha enviado el formulario (submit) 119 | if (Input::hasPost('menus')) { 120 | 121 | if ($menu->update(Input::post('menus'))) { 122 | Flash::valid('Operación exitosa'); 123 | //enrutando por defecto al index del controller 124 | return Redirect::to(); 125 | } 126 | Flash::error('Falló Operación'); 127 | return; 128 | } 129 | 130 | //Aplicando la autocarga de objeto, para comenzar la edición 131 | $this->menus = $menu->find_by_id((int) $id); 132 | 133 | } 134 | 135 | /** 136 | * Eliminar un menú 137 | * 138 | * @param int $id (requerido) 139 | */ 140 | public function del($id) 141 | { 142 | if ((new Menus)->delete((int) $id)) { 143 | Flash::valid('Operación exitosa'); 144 | } else { 145 | Flash::error('Falló Operación'); 146 | } 147 | 148 | //enrutando por defecto al index del controller 149 | return Redirect::to(); 150 | } 151 | } 152 | 153 | ``` 154 | 155 | ## Vistas 156 | 157 | Agregamos las vistas... 158 | 159 | [app]/views/menus/index.phtml 160 | ```php 161 |
162 | 163 |

Menús

164 | 173 | 174 | // ejemplo manual de paginado, existen partials listos en formato digg, clasic,... 175 | prev) echo Html::linkAction("index/$listMenus->prev/", '<< Anterior |') ?> 176 | next) echo Html::linkAction("index/$listMenus->next/", 'Proximo >>') ?> 177 |
178 | ``` 179 | 180 | [app]/views/menus/create.phtml 181 | 182 | ```php 183 | 184 |

Crear menú

185 | 186 | 187 | 188 | 190 | 191 | 193 | 194 | 195 | 196 | 197 | ``` 198 | [app]/views/menus/edit.phtml 199 | ```php 200 | 201 |

Editar menú

202 | 203 | 204 | 205 | 206 | 207 | 208 | ``` 209 | 210 | 211 | ## Probando el CRUD 212 | 213 | Ahora sólo resta probar todo el código que hemos generado, en este punto es 214 | importante conocer el comportamiento de las [URL's en KumbiaPHP](http://wiki.kumbiaphp.com/Hola_Mundo_KumbiaPHP_Framework#KumbiaPHP_URLS) . 215 | 216 | * index es la acción para listar http://localhost/menus/index/ 217 | NOTA: index/ se puede pasar de forma implícita o no. KumbiaPHP en caso que no 218 | se le pase una accion, buscara por defecto un index, es decir si colocamos: 219 | http://localhost/menus/ 220 | * create crea un menú en la Base de Datos http://localhost/menus/create/ 221 | * Las acciones del y edit a ambas se debe entrar desde el index, ya que reciben el parámetros a editar o borrar según el caso. -------------------------------------------------------------------------------- /es/installing-kumbiaphp-apache-nginx.md: -------------------------------------------------------------------------------- 1 | # Instalación de KumbiaPHP en Servidores Web (Apache y Nginx) para GNU/Linux (Debian, Ubuntu y derivados) 2 | 3 | Esta sección proporciona instrucciones para instalar y configurar KumbiaPHP utilizando **Apache** o **Nginx** como servidor web en distribuciones Linux como Ubuntu y Debian. Al finalizar, tendrás una instalación funcional de KumbiaPHP lista para el desarrollo. 4 | 5 | > ⚠️ **Advertencia** 6 | > 7 | > Esta instalación es un entorno de pruebas, pensado para experimentar con KumbiaPHP en un servidor local. No está recomendada para el desarrollo de aplicaciones que vayan a ser publicadas en producción. 8 | 9 | ## Requisitos Previos 10 | 11 | * **Servidor Web** (Apache HTTP o Nginx) instalado y en ejecución. 12 | * **PHP 8.0** (o posterior) con las extensiones necesarias: `php-mbstring`, `php-xml`, `php-json`, etc. 13 | * Conocimientos básicos de comandos de terminal (`sudo`, mover archivos, etc.). 14 | 15 | ## Descargar y Descomprimir KumbiaPHP 16 | 17 | 1. Dirígete a la carpeta donde se alojarán los archivos del proyecto, por ejemplo `/var/www`: 18 | 19 | ```bash 20 | cd /var/www 21 | ``` 22 | 23 | 2. **Descarga** el archivo `.tar.gz` más reciente desde el repositorio oficial: 24 | 25 | ```bash 26 | wget https://github.com/KumbiaPHP/KumbiaPHP/archive/v1.2.1.tar.gz 27 | ``` 28 | 29 | 3. **Descomprime** el contenido: 30 | 31 | ```bash 32 | tar -xzvf v1.2.1.tar.gz 33 | ``` 34 | 35 | 4. (Opcional) **Renombra** la carpeta resultante: 36 | 37 | ```bash 38 | mv KumbiaPHP-1.2.1 kumbiafw 39 | ``` 40 | 41 | ## Configuración Específica del Servidor 42 | 43 | ### Apache 44 | 45 | 1. Crea un nuevo archivo de configuración en `/etc/apache2/sites-available/`, por ejemplo `kumbiafw.conf`: 46 | 47 | ```apache 48 | 49 | ServerName kumbia.fw 50 | DocumentRoot /var/www/kumbiafw/default/public 51 | 52 | 53 | AllowOverride All 54 | Require all granted 55 | 56 | 57 | ErrorLog ${APACHE_LOG_DIR}/kumbiafw-error.log 58 | CustomLog ${APACHE_LOG_DIR}/kumbiafw-access.log combined 59 | 60 | ``` 61 | 62 | * Cambia `kumbia.fw` por el dominio o hostname local que desees. 63 | * Ajusta la ruta de `DocumentRoot` a la ubicación donde descomprimiste KumbiaPHP. 64 | 65 | 2. Activa el nuevo sitio y el módulo `rewrite`: 66 | 67 | ```bash 68 | sudo a2ensite kumbiafw.conf 69 | sudo a2enmod rewrite 70 | sudo systemctl reload apache2 71 | ``` 72 | 73 | #### ¿Por qué es importante `mod_rewrite`? 74 | 75 | `mod_rewrite` es un módulo de Apache que permite reescribir las URLs que utilizan los usuarios. KumbiaPHP encapsula esta funcionalidad, permitiéndote usar URLs limpias y legibles, como las que vemos en blogs o aplicaciones modernas (sin signos como `?`, `&`, ni extensiones como `.php`, `.asp`, `.aspx`, etc.). 76 | 77 | Además, con `mod_rewrite`, KumbiaPHP mejora la seguridad de la aplicación al restringir el acceso directo a directorios y archivos internos. Solo el contenido del directorio `public/` será accesible por los usuarios, garantizando que la lógica de negocio y las clases del sistema permanezcan protegidas. 78 | 79 | También mejora la indexación en motores de búsqueda, lo que es beneficioso para la visibilidad de tus aplicaciones. 80 | 81 | ### Nginx 82 | 83 | 1. Crea un nuevo bloque de servidor en `/etc/nginx/sites-available/kumbiafw`: 84 | 85 | **Usando `$_SERVER['PATH_INFO']`:** 86 | 87 | ```nginx 88 | server { 89 | listen 80; 90 | server_name kumbia.fw; 91 | root /var/www/kumbiafw/default/public; 92 | index index.php index.html index.htm; 93 | 94 | location / { 95 | try_files $uri $uri/ /index.php$uri?$args; 96 | } 97 | 98 | location ~ \.php { 99 | # Extract PATH_INFO after index.php 100 | fastcgi_split_path_info ^(.+\.php)(/.*)$; 101 | 102 | fastcgi_pass 127.0.0.1:9000; 103 | # fastcgi_pass unix:/run/php/php-fpm.sock; 104 | 105 | include fastcgi_params; 106 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 107 | fastcgi_param PATH_INFO $fastcgi_path_info; 108 | } 109 | 110 | location ~ /\.ht { 111 | deny all; 112 | } 113 | } 114 | ``` 115 | 116 | **Usando `$_GET['_url']`:** 117 | 118 | ```nginx 119 | server { 120 | listen 80; 121 | server_name kumbia.fw; 122 | root /var/www/kumbiafw/default/public; 123 | index index.php index.html index.htm; 124 | 125 | location / { 126 | try_files $uri $uri/ /index.php?_url=$uri&$args; 127 | } 128 | 129 | location ~ \.php { 130 | fastcgi_pass 127.0.0.1:9000; 131 | # fastcgi_pass unix:/run/php/php-fpm.sock; 132 | 133 | include fastcgi_params; 134 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 135 | } 136 | 137 | location ~ /\.ht { 138 | deny all; 139 | } 140 | } 141 | ``` 142 | 143 | * Cambia `server_name` y `root` según tus necesidades. 144 | * Asegúrate de que el socket de PHP-FPM corresponde a tu versión de PHP. 145 | 146 | > ℹ️ **Importante** 147 | > Si usas otra versión de PHP (por ejemplo 8.1), ajusta la ruta del socket en Nginx (`fastcgi_pass`) o el módulo correspondiente en Apache. 148 | > Algunas instrucciones pueden variar ligeramente según la versión de Ubuntu o Debian que utilices. 149 | 150 | 2. Activa el nuevo sitio: 151 | 152 | ```bash 153 | sudo ln -s /etc/nginx/sites-available/kumbiafw /etc/nginx/sites-enabled/ 154 | sudo nginx -t 155 | sudo systemctl reload nginx 156 | ``` 157 | 158 | ## Configurar Permisos 159 | 160 | Asegúrate de que el usuario del servidor web (generalmente `www-data`) tenga acceso a los archivos: 161 | 162 | ```bash 163 | sudo chown -R www-data:www-data /var/www/kumbiafw 164 | sudo find /var/www/kumbiafw -type d -exec chmod 755 {} \; 165 | sudo find /var/www/kumbiafw -type f -exec chmod 644 {} \; 166 | ``` 167 | 168 | * Las carpetas tienen permisos `755`. 169 | * Los archivos tienen permisos `644`. 170 | 171 | ## Probar la Instalación 172 | 173 | 1. Edita tu archivo `/etc/hosts` para mapear el nombre del servidor: 174 | 175 | ```bash 176 | sudo nano /etc/hosts 177 | ``` 178 | 179 | Añade esta línea: 180 | 181 | ``` 182 | 127.0.0.1 kumbia.fw 183 | ``` 184 | 185 | 2. Abre tu navegador y visita `http://kumbia.fw`. Deberías ver la página de bienvenida de KumbiaPHP. 186 | 187 | ![Instalación exitosa](../images/welcome-page.jpg) 188 | 189 | ## Verificación con un Controlador y Vista 190 | 191 | 1. Crea un archivo `app/controllers/test_controller.php`: 192 | 193 | ```php 194 | date = date('Y-m-d H:i:s'); 210 | } 211 | } 212 | ``` 213 | 214 | 2. Y su correspondiente vista en `app/views/test/index.phtml`: 215 | 216 | ```php 217 |

Welcome to KumbiaPHP!

218 | Today's date and time is: 219 | ``` 220 | 221 | 3. Visita `http://kumbia.fw/test` en tu navegador para ver el mensaje de bienvenida. 222 | 223 | ![Mensaje de bienvenida](../images/test-welcome-message.jpg) 224 | -------------------------------------------------------------------------------- /es/preface.md: -------------------------------------------------------------------------------- 1 | # Prefacio 2 | 3 | ## Agradecimientos 4 | Este manual está dedicado a quienes, con su tiempo y apoyo (sea mucho o poco), han contribuido a que este framework 5 | mejore día a día. A toda la comunidad que rodea a KumbiaPHP, con sus preguntas, reportes de errores (bugs), aportes y 6 | críticas, ¡muchas gracias! 7 | 8 | ## Acerca del Manual 9 | El libro de KumbiaPHP busca mostrar cómo este framework puede ayudar en el trabajo diario de un desarrollador. Permite 10 | descubrir las distintas facetas de KumbiaPHP y conocer por qué puede ser la herramienta que estaba esperando para 11 | iniciar su proyecto. Se encuentra en constante desarrollo (diseño gráfico, revisión ortográfica y gramatical, 12 | contenidos, etc.), al igual que el framework, por lo que se recomienda mantener siempre la última versión actualizada. 13 | 14 | En esta edición del manual se han realizado grandes cambios respecto a la anterior. Gracias a la comunidad se 15 | identificaron dudas recurrentes en el grupo, el foro y el chat. También se detectó el uso inadecuado del patrón MVC y la 16 | falta de aprovechamiento de las facilidades de la Programación Orientada a Objetos (POO). Se ha procurado abordar estos 17 | aspectos y mejorar la comprensión de uso, de modo que puedan crearse aplicaciones más mantenibles y de mayor calidad. 18 | 19 | ## Acerca de KumbiaPHP 20 | KumbiaPHP es un producto latino para el mundo. La programación debería ser tan placentera como un baile, y KumbiaPHP 21 | hace que programar sea tan ameno como bailar. Es un framework de libre uso bajo licencia New BSD, por lo que puedes 22 | utilizarlo en tus proyectos respetando los términos de dicha licencia. Se sugiere siempre usar versiones estables y lo 23 | más recientes posibles, ya que incluyen correcciones, nuevas funcionalidades y mejoras significativas. 24 | 25 | ## Sobre la comunidad 26 | La comunidad de KumbiaPHP nació principalmente a partir de desarrolladores hispanohablantes, lo que dio origen a un 27 | framework completamente en español. Sin embargo, hoy en día también existe una comunidad de habla inglesa que contribuye 28 | a la expansión internacional de KumbiaPHP. Con el tiempo, se han implementado diversos canales de comunicación como una 29 | lista de correo, un foro, un canal de IRC, una Wiki y ahora también un espacio en Slack, que resulta ser el medio más 30 | ágil para recibir soporte y conversar con otros usuarios.Este esfuerzo colaborativo hace que la comunidad sea esencial 31 | para enriquecer y mejorar KumbiaPHP. 32 | Para más información, visita el [Sitio web oficial de KumbiaPHP](https://www.kumbiaphp.com). 33 | 34 | ## ¿Por qué usar KumbiaPHP Framework? 35 | Muchas personas se preguntan: ¿cómo funciona este framework?, ¿otro más?, ¿será fácil?, ¿qué tan potente es?, etc. A 36 | continuación, algunas razones para utilizar KumbiaPHP: 37 | 38 | - Es muy fácil de usar (Zero-Config). Empezar con KumbiaPHP es sencillísimo: basta con descomprimir y comenzar a 39 | trabajar. Esta filosofía se conoce como “Convención sobre Configuración”. 40 | - Agiliza el trabajo. Crear una aplicación muy funcional con KumbiaPHP puede tomar solo minutos u horas, lo que permite 41 | complacer a los clientes sin sacrificar demasiado tiempo. Gracias a las múltiples herramientas que ofrece, se puede 42 | hacer más en menos tiempo. 43 | - Separa la lógica de la presentación. Una de las mejores prácticas en el desarrollo web es separar la lógica de datos 44 | de la presentación. Con KumbiaPHP, implementar el patrón MVC (Modelo, Vista y Controlador) es sencillo, lo que 45 | facilita el mantenimiento y la escalabilidad de las aplicaciones. 46 | - Reduce el uso de otros lenguajes. Gracias a los Helpers y a patrones como ActiveRecord, se minimiza la necesidad de 47 | escribir HTML y SQL (aunque sea en menor porcentaje). KumbiaPHP se encarga de esas tareas, logrando un código más 48 | claro, natural y menos propenso a errores. 49 | - ¡Habla español (y también inglés, con más idiomas próximamente)! 50 | KumbiaPHP inició con documentación, mensajes de error y archivos de configuración en español, pero se está 51 | introduciendo gradualmente un sistema de internacionalización (i18n) para brindar soporte multilenguaje y llegar a una 52 | comunidad global cada vez más amplia. 53 | - Su curva de aprendizaje es muy corta, especialmente para quienes ya cuenten con experiencia en Programación Orientada 54 | a Objetos. 55 | - Parece un juego. Sin notarlo, se aplican múltiples patrones de diseño, que facilitan el trabajo al abstraer, reducir 56 | código y hacer la aplicación más sencilla de entender. Trabajar con KumbiaPHP implica aplicar muchos patrones de 57 | manera casi natural. 58 | - Es Software Libre. No hay que preocuparse por licencias adicionales, y KumbiaPHP promueve las comunidades de 59 | aprendizaje, donde el conocimiento es de todos y cada quien sabe cómo aprovecharlo mejor. 60 | - Permite crear aplicaciones robustas. Las aplicaciones actuales requieren arquitecturas sólidas. KumbiaPHP ofrece una 61 | arquitectura sencilla de aprender e implementar, sin complicar con conceptos excesivos y sin sacrificar calidad. 62 | 63 | ## ¿Qué aporta KumbiaPHP? 64 | KumbiaPHP es un esfuerzo por producir un framework que reduzca el tiempo de desarrollo de una aplicación web, sin 65 | repercutir negativamente en los programadores, apoyándose en principios clave que siempre tenemos presentes: 66 | 67 | - KISS («Mantenlo simple, estúpido» o Keep It Simple, Stupid). 68 | - DRY (Don’t Repeat Yourself, también conocido como “Una vez y solo una”). 69 | - Convención sobre configuración. 70 | - Velocidad. 71 | 72 | Además, KumbiaPHP se fundamenta en las siguientes premisas: 73 | 74 | - Fácil de aprender. 75 | - Fácil de instalar y configurar. 76 | - Compatible con muchas plataformas. 77 | - Listo para aplicaciones comerciales. 78 | - Sencillo en la mayoría de los casos, pero flexible para adaptarse a situaciones más complejas. 79 | - Soporte de numerosas características para aplicaciones web actuales. 80 | - Aplicación de prácticas y patrones de programación productivos y eficientes. 81 | - Producción de aplicaciones fáciles de mantener. 82 | - Basado en Software Libre. 83 | 84 | El objetivo principal es lograr aplicaciones prácticas para el usuario final y no solo para el programador. La mayoría 85 | de las tareas que consumen tiempo al desarrollador deberían automatizarse con KumbiaPHP, de modo que se pueda enfocar en 86 | la lógica de negocio de su aplicación. No se debería reinventar la rueda cada vez que se inicia un nuevo proyecto de 87 | software. 88 | 89 | Para lograr estos objetivos, KumbiaPHP está escrito en PHP5 (plenamente compatible con PHP 8.0) y ha sido probado en 90 | aplicaciones reales que abarcan diversas áreas con una amplia variedad de demandas y funcionalidades. Es compatible con 91 | las bases de datos más utilizadas en la actualidad: 92 | 93 | - MySQL 94 | - PostgreSQL 95 | - Oracle 96 | - SQLite 97 | 98 | El modelo de objetos de KumbiaPHP se aplica en las siguientes capas: 99 | 100 | - [Lógica de la aplicación](model.md) 101 | - [Abstracción de la base de datos y mapeo Objeto-Relacional](active-record.md) 102 | 103 | Entre las características comunes de las aplicaciones web que KumbiaPHP automatiza se encuentran: 104 | 105 | - Plantillas (TemplateView). 106 | - Validación y persistencia de formularios. 107 | - Administración de caché. 108 | - Scaffolding. 109 | - Front Controller. 110 | - Interacción AJAX. 111 | - Generación de formularios. 112 | - Seguridad. 113 | -------------------------------------------------------------------------------- /en/first-app.md: -------------------------------------------------------------------------------- 1 | # My first app with KumbiaPHP 2 | 3 | After you are ready with the KumbiaPHP installation, you can see the welcome page. Now it is time to create your first Hello World application. The goal is that you understand the basic components of the MVC (Model-View-Controller) architecture. 4 | 5 | ## Hello KumbiaPHP! 6 | 7 | Now write the famous "Hello World!" but with a small change: say "Hello KumbiaPHP!". Thinking about this, remember the MVC model, according to this, KumbiaPHP should accept a petition, seeking driver and, in this, an action that serves the request. Then, KumbiaPHP uses that information to find the view associated with the request. 8 | 9 | ## Controller 10 | 11 | Now add content to the controller app/controllers/controller/saludo_controller.php 12 | 13 | ```php 14 | Hello KumbiaPHP! 39 | ``` 40 | 41 | Then try to access the following URL: http://localhost/kumbiaphp/saludo/hola/ and the result must be as shown Figure 2.2. 42 | 43 | ![](../images/image06.png) Figure 2.2: View contents of hello.phtml 44 | 45 | ## KumbiaPHP and URLs 46 | 47 | To understand the functioning of the framework it is important to understand their URLs, Figure 2.3 shows a typical URL in KumbiaPHP. 48 | 49 | ![](../images/image08.png) Figure 2.3: URL in KumbiaPHP 50 | 51 | In KumbiaPHP .php extensions there is this because in the first instance there is rewriting of URLs and also has a front-controller responsible for receiving all requests (more I will later explain in detail). 52 | 53 | Any other information passed by URL is taken as the parameter of the action, with regard to our application as shown in Figure 2.4. 54 | 55 | ![](../images/image05.png) Figure 2.4: URL with parameters 56 | 57 | This is useful to avoid having to send form parameters GET? var = value & var2 = value2 (that is, in the traditional way how PHP has been used), which reveals information about the architecture of software that is available on the server. In addition, make that our URL look bad and ugly for SEO. 58 | 59 | ## Add more content 60 | 61 | We will add some dynamic to our project, so it's not so boring. We will show the time and date, using the date() function. 62 | 63 | We changed a bit the driver *app/controllers/greeting_controller.php* 64 | 65 | ```php 66 | date = date("Y-m-d H:i"); 76 | } 77 | } 78 | ``` 79 | 80 | KumbiaPHP implements the instance variables, which means that all attributes (public) defined in the controller, it happened automatically in sight, in the preceding code have the attribute $this->date this happened to the view as a variable called $date. 81 | 82 | In the view that was created in the section 2.1.3.3 and Add. 83 | 84 | ```php 85 |

Hello KumbiaPHP!

86 | 87 | ``` 88 | 89 | Now, if we http://localhost/kumbiaphp/greeting/hello/, we will get the time and date from the time the request is made as shown in Figure 2.5. 90 | 91 | ![](../images/image02.png) Figure 2.5: Time and date of request 92 | 93 | To add warmth to the topic, we will ask the user name via parameter 2.1.3.4, go back to edit the controller *greeting_controller.php* 94 | 95 | ```php 96 | date = date("Y-m-d H:i"); 109 | $this->name = $name; 110 | } 111 | } 112 | ``` 113 | 114 | Edit the view *app/views/greeting/hello.phtml* 115 | 116 | ```php 117 |

Hello , How nice is to use KumbiaPHP! 118 | right?

119 | 120 | ``` 121 | 122 | If we now go to *http://localhost/kumbiaphp/greeting/hello/CaChi/*, show us in the web browser the greeting along with the registered name and the current date, as shown in Figure 2.6. 123 | 124 | ![](../images/image09.png) Figure 2.6: Greeting to the user 125 | 126 | ## Repeating history 127 | 128 | Now go another action called goodbye() and as the name suggests will do the reverse process to greet, i.e. Say goodbye to users. 129 | 130 | ```php 131 | date = date("Y-m-d H:i"); 142 | $this->name = $name; 143 | } 144 | /** 145 | * Method to say goodbye 146 | */ 147 | public function goodbye() { 148 | 149 | } 150 | } 151 | ``` 152 | 153 | Add a new view to present the contents of the action goodbye() and if we recall what was explained in the section 2.1.3.3 we should create a view *app/views/saludo/adios.phtml* with the following contents. 154 | 155 | ```php 156 |

Ops! has gone :(

157 | 158 | ``` 159 | 160 | If you enter the following link *http://localhost/kumbiaphp/greeting/goodbye/* you will see a new text, and a link to the hello() action, as shown in Figure 2.7. 161 | 162 | ![](../images/image04.png) Figure 2.7: View goodbye to the user. 163 | 164 | Html: link (), is one of the many helper offering KumbiaPHP to facilitate at the time of scheduled hearings. We could write the HTML code directly, by placing *[back to say hello](kumbiaphp/saludo/hola/CaChi/)*, but this can lead to a problem, imagine you would rename his project in kumbiaphp demo, we would have to modify all the links, KumbiaPHP helpers solve these problems. 165 | 166 | To write the code of our "Hello KumbiaPHP!" don't need but a controller and a view. We don't need models, since we are not working with information from a database or other type of more complex information processing. 167 | 168 | We are located in the directory */path/to/kumbiaphp/app/controllers/*. Here are our drivers (for more details, read the documentation on the app directory). To create a handler, it is important to keep in mind the conventions of name which uses the Framework. We will call our driver *saludo_controller.php*. Note the suffix *_controller.php* this is part of the Naming Convention, and makes that KumbiaPHP identifies this file as a driver. -------------------------------------------------------------------------------- /es/configuration.md: -------------------------------------------------------------------------------- 1 | ## Configuración: Archivo `config/config.php` 2 | 3 | El archivo `default/app/config/config.php` es un componente central de configuración para cualquier aplicación KumbiaPHP. 4 | A través de este archivo, puedes personalizar los ajustes clave de la aplicación, incluyendo su nombre, base de datos, 5 | formato de fechas, depuración, y más. 6 | 7 | En el archivo `config.php`, todas las opciones están organizadas bajo el índice 'application'. Esto permite que las 8 | configuraciones de la aplicación sean fácilmente accesibles y modificables en un solo lugar. Además, es posible agregar 9 | más índices para definir configuraciones adicionales o incluir archivos de configuración específicos. Esto proporciona 10 | flexibilidad para gestionar distintos aspectos del proyecto y personalizar completamente la aplicación según las 11 | necesidades del desarrollador. 12 | 13 | ```php 14 | [ 21 | 'name' => 'KUMBIAPHP PROJECT', 22 | 'database' => 'development', 23 | 'dbdate' => 'YYYY-MM-DD', 24 | 'debug' => 'On', 25 | 'log_exceptions' => 'On', 26 | //'cache_template' => 'On', 27 | 'cache_driver' => 'file', 28 | 'metadata_lifetime' => '+1 year', 29 | 'namespace_auth' => 'default', 30 | //'routes' => '1', 31 | ], 32 | ]; 33 | 34 | ``` 35 | 36 | Aquí te mostramos una explicación detallada de cada parámetro. 37 | 38 | ### Nombre de la Aplicación 39 | 40 | El nombre de la aplicación, representado por el parámetro `name`, identifica el proyecto en el entorno KumbiaPHP. Aunque 41 | no afecta la funcionalidad directamente, se utiliza para diferenciar y personalizar el proyecto. 42 | 43 | ### Base de Datos 44 | 45 | El parámetro `database` determina cuál configuración de base de datos se debe utilizar para la aplicación. Este valor 46 | debe coincidir con uno de los identificadores en el archivo `databases.php`, como "development" o "production". Esto 47 | permite alternar entre distintos ambientes con facilidad. 48 | 49 | ### Formato de Fecha 50 | 51 | El parámetro `dbdate` especifica el formato de fecha predeterminado para la aplicación, utilizando la notación estándar 52 | `YYYY-MM-DD`. Esta configuración garantiza que todas las fechas en la aplicación sean consistentes. 53 | 54 | ### Depuración (Debug) 55 | 56 | La opción `debug` activa o desactiva la visualización de errores en pantalla. En modo "On", los errores se muestran para 57 | ayudar en el proceso de desarrollo. En producción, debe estar desactivado ("Off") para evitar la exposición de errores a 58 | los usuarios finales. 59 | 60 | ### Registro de Excepciones 61 | 62 | El parámetro `log_exceptions` determina si las excepciones capturadas se muestran en pantalla. Esto puede ser útil para 63 | rastrear problemas durante el desarrollo, pero debe desactivarse en producción para evitar revelar información sensible. 64 | 65 | ### Caché de Plantillas 66 | 67 | El parámetro `cache_template` puede habilitarse para almacenar las plantillas en caché, lo que mejora el rendimiento al 68 | reducir la necesidad de recompilarlas. 69 | 70 | ### Controlador de Caché 71 | 72 | La opción `cache_driver` permite seleccionar el mecanismo de almacenamiento en caché a usar. Entre las opciones 73 | disponibles se encuentran: 74 | - **file**: Archivos en el sistema de almacenamiento. 75 | - **sqlite**: Una base de datos SQLite. 76 | - **memsqlite**: Una base de datos SQLite en memoria. 77 | 78 | ### Tiempo de Vida de la Metadata 79 | 80 | El parámetro `metadata_lifetime` define cuánto tiempo los metadatos almacenados en caché deben ser considerados válidos. 81 | Se acepta cualquier formato compatible con la función `strtotime()`, como "+1 year". 82 | 83 | ### Espacio de Nombres para Autenticación 84 | 85 | El `namespace_auth` permite definir un espacio de nombres predeterminado para el sistema de autenticación, lo que 86 | facilita la gestión de múltiples espacios según el contexto de la aplicación. 87 | 88 | ### Rutas Personalizadas 89 | 90 | El parámetro `routes` puede habilitarse para permitir rutas personalizadas a través del archivo `routes.php`. Esto 91 | ofrece flexibilidad al reorganizar la estructura de URLs en la aplicación. 92 | 93 | ### Consideraciones Generales 94 | 95 | Al configurar este archivo, es fundamental asegurarse de que los parámetros como `debug` y `log_exceptions` estén 96 | deshabilitados en entornos de producción para mantener la seguridad. Además, elegir el mecanismo de caché y formato de 97 | fechas adecuado puede mejorar significativamente el rendimiento y la consistencia de la aplicación. 98 | 99 | ## Configuración: Archivo `config/exception.php` (v 1.2) 100 | 101 | El archivo `config/exception.php` en KumbiaPHP permite configurar las direcciones IP desde las cuales se mostrarán los 102 | detalles de las excepciones en lugar de un error 404 genérico. Esta funcionalidad es especialmente útil durante la fase 103 | de desarrollo, donde los desarrolladores necesitan ver la traza de errores y detalles específicos para depurar de manera 104 | efectiva. 105 | 106 | ### Ubicación del Archivo 107 | El archivo de configuración se encuentra en la ruta `default/app/config/exception.php`. 108 | 109 | ### Contenido del Archivo 110 | El archivo tiene un formato de arreglo PHP y contiene una única clave `trustedIp`, que es un array de direcciones IP. A 111 | continuación se muestra el contenido por defecto del archivo: 112 | 113 | ```php 114 | [] 120 | ]; 121 | ``` 122 | 123 | ### Configuración de IPs Confiables 124 | El array `trustedIp` debe ser configurado con las direcciones IP desde las cuales se permitirá mostrar los detalles 125 | completos de las excepciones. Esto es útil cuando se quiere permitir que ciertos desarrolladores o equipos de desarrollo 126 | accedan a esta información desde ubicaciones específicas. Esta característica está disponible desde la versión 1.2.0 en 127 | adelante. 128 | 129 | **Ejemplo:** 130 | ```php 131 | ['192.168.1.100', '203.0.113.5'] 136 | ]; 137 | ``` 138 | En este ejemplo, los detalles de las excepciones se mostrarán únicamente a los usuarios que accedan desde las IPs 139 | `192.168.1.100` y `203.0.113.5`. 140 | 141 | ### Comportamiento por Defecto 142 | Por defecto, el arreglo `trustedIp` está vacío. Esto significa que, a menos que se configure, los detalles de las 143 | excepciones solo se mostrarán en el ambiente localhost. Si se deja vacío, solo las conexiones desde `127.0.0.1` o `::1` 144 | (localhost en IPv6) podrán ver los detalles completos de las excepciones. 145 | 146 | ### Importancia de la Configuración 147 | Esta configuración es crucial para mantener la seguridad en entornos de producción. Mostrar detalles de excepciones a 148 | usuarios no autorizados puede exponer información sensible y vulnerabilidades potenciales. Por lo tanto, se recomienda mantener esta lista restringida solo a IPs de confianza y utilizarla con cuidado. 149 | 150 | ### Consideraciones Adicionales 151 | - **Seguridad:** Asegúrate de que solo se añadan direcciones IP confiables para evitar posibles filtraciones de 152 | información sensible. 153 | - **Entorno de Producción:** En un entorno de producción, es recomendable desactivar la visualización de detalles de 154 | excepciones para todos los usuarios o restringirla estrictamente a direcciones IP internas. 155 | - **Mantenimiento:** Revisa y actualiza periódicamente la lista de IPs en `trustedIp` para reflejar cambios en la 156 | infraestructura o equipo de desarrollo. 157 | 158 | Con esta configuración, KumbiaPHP permite un manejo flexible y seguro de la depuración de excepciones, adaptándose a las 159 | necesidades específicas de cada entorno de desarrollo y producción. 160 | -------------------------------------------------------------------------------- /en/controller.md: -------------------------------------------------------------------------------- 1 | # Controller 2 | 3 | In the KumbiaPHP Framework, the controller layer contains the code that connects business logic with presentation logic. 4 | It's divided into various components used for different purposes: 5 | 6 | - Actions verify the integrity of requests and prepare the data required by the presentation layer. 7 | - The `Input` and `Session` classes provide access to request parameters and the user's persistent data. These are 8 | frequently used in the controller layer. 9 | - Filters are pieces of code executed for each request, before and/or after a controller, and even before and/or after 10 | an action. For instance, security and validation filters are commonly used in web applications. 11 | 12 | This chapter describes all these components. For a basic page, you'll likely only need to write a few lines of code in 13 | the action class, and that's it. The other controller components are only used in specific situations. 14 | 15 | ## Actions 16 | 17 | Actions are fundamental in the application because they define the flow in which the application will respond to 18 | specific requests. Actions utilize the model and define variables for the view. When a web request is made in a 19 | KumbiaPHP application, the URL defines an action and the request parameters. Refer to the 20 | [KumbiaPHP and its URLs](first-app.md#kumbiaphp-y-sus-urls) section. 21 | 22 | Actions are methods of a controller class, called `ClassController`, which inherits from the `AppController` class. 23 | They can be grouped into modules or not. 24 | 25 | ### Actions and Views 26 | 27 | Each time an action is executed, KumbiaPHP searches for a view with the same name as the action. This behavior is set 28 | by default. Usually, requests need to respond to the client who made the request. Therefore, if we have an action called 29 | `greeting()`, there should be an associated view called `greeting.phtml`. A more comprehensive chapter will explain 30 | views in KumbiaPHP. 31 | 32 | ### Getting Values from an Action 33 | 34 | KumbiaPHP URLs consist of several parts, each serving a specific function. To access the values from a controller that 35 | are sent in the URL, you can use some properties defined in the controller. 36 | 37 | Consider the following URL: 38 | 39 | http://www.example.com/news/show/12/ 40 | 41 | - Controller: News 42 | - Action: show 43 | - Parameters: 12 44 | 45 | ```php 46 | controller_name; // news 57 | echo $this->action_name; // show 58 | // An array with all parameters sent to the action 59 | var_dump($this->parameters); 60 | } 61 | } 62 | ``` 63 | 64 | It's essential to note the relationship between the parameters sent via URL and the action. In this sense, KumbiaPHP has 65 | a feature that makes executing actions secure: parameter transmission is limited to what is defined in the method 66 | (action). This means that all parameters sent via URL are arguments received by the action. See the 67 | [KumbiaPHP and its URLs](first-app.md#kumbiaphp-y-sus-urls) section. 68 | 69 | In the previous example, the action `show($id)` defined only one parameter. If this parameter isn't sent, or if 70 | additional parameters are attempted, KumbiaPHP will throw an exception (in production, it shows a 404 error). This is 71 | the framework's default behavior, but it can be adjusted for different scenarios depending on the application's purpose. 72 | 73 | In the "Hello World" example, you can practice the above by sending additional parameters to the `hello($name)` method, 74 | which only accepts one parameter (the name). If you visit `http://localhost/kumbiaphp/greeting/hello/CaChi/additional`, 75 | you'll see the exception generated by KumbiaPHP, as shown in Figure 3.1. 76 | 77 | ![](../images/image13.png) 78 | 79 | Figure 3.1: Exception due to incorrect number of parameters. 80 | 81 | Following the same example, suppose we want the execution of the `hello()` action to ignore the number of parameters 82 | sent via URL. In that case, we need to tell KumbiaPHP to disregard the number of parameters passed in the URL by setting 83 | the `$limit_params` attribute to `FALSE`. 84 | 85 | ```php 86 | ¡Hola KumbiaPHP! 56 | ``` 57 | 58 | Al acceder a `http://127.0.0.1:8001/greetings/hello/`, veremos en pantalla el mensaje como se muestra en la figura 1. 59 | 60 | ![](../images/kumbiaphp-greetings.png) 61 | *Figura 1: Contenido de la vista hello.phtml* 62 | 63 | ## Cómo funcionan las URLs en KumbiaPHP 64 | 65 | En KumbiaPHP, las URLs son la forma en que se indica qué controlador y qué acción se deben ejecutar. Gracias a su sistema de reescritura de URLs y al uso de un front-controller, las direcciones son más limpias, fáciles de leer y amigables para [SEO](https://es.wikipedia.org/wiki/Posicionamiento_en_buscadores). 66 | 67 | ### Anatomía de una URL en KumbiaPHP 68 | 69 | En una URL típica, cada segmento tiene un significado: el dominio, el controlador, la acción y, opcionalmente, los parámetros. 70 | 71 | ![](../images/kumbia-url-anatomy.png) 72 | *Figura 2: URL en KumbiaPHP* 73 | 74 | En KumbiaPHP: 75 | 76 | * No se utilizan extensiones `.php` porque todas las peticiones son procesadas por el front-controller. 77 | * Los segmentos adicionales de la URL se interpretan como argumentos que se pasan directamente al método de la acción. 78 | 79 | ### Parámetros en la URL 80 | 81 | Cualquier valor que aparezca después del nombre de la acción se considera un **parámetro**. Estos parámetros llegan como argumentos al método correspondiente en el controlador. 82 | 83 | Ejemplo: 84 | 85 | ![](../images/kumbia-url-anatomy-params.png) 86 | *Figura 3: URL con parámetros* 87 | 88 | De esta forma, en lugar de usar parámetros tradicionales como `?var=valor&var2=valor2` (largos y poco legibles), KumbiaPHP ofrece **URLs más claras y organizadas**, lo que evita exponer detalles internos del sistema y mejora la experiencia de usuario y el SEO. 89 | 90 | ## Haciendo el saludo más dinámico 91 | 92 | Para hacerlo más dinámico, mostraremos la **fecha y hora actual**. Editamos el controlador: 93 | 94 | ```php 95 | date = date("Y-m-d H:i"); 109 | } 110 | } 111 | ``` 112 | 113 | En KumbiaPHP, todas las **variables públicas** definidas en el controlador se transmiten automáticamente a la vista como 114 | variables disponibles. 115 | En este caso, `$this->date` estará disponible en la vista como `$date`. 116 | 117 | Editamos `app/views/greetings/hello.phtml`: 118 | 119 | ```php 120 |

¡Hola KumbiaPHP!

121 | 122 | ``` 123 | 124 | Ahora, al entrar nuevamente a `http://127.0.0.1:8001/greetings/hello/`, veremos la fecha y hora actual (figura 4). 125 | 126 | ![](../images/kumbiaphp-greetings-date.png) 127 | *Figura 4: Hora y fecha de la petición* 128 | 129 | > 💡 **Nota**: La sintaxis corta `` es equivalente a ``, pero resulta más concisa y legible al momento de imprimir variables en las vistas. 130 | 131 | ### Pasando parámetros en la URL 132 | 133 | Podemos mejorar aún más el saludo solicitando al usuario su nombre como parámetro. Modificamos el controlador: 134 | 135 | ```php 136 | date = date("Y-m-d H:i"); 151 | $this->name = $name; 152 | } 153 | } 154 | ``` 155 | 156 | Editamos la vista `hello.phtml`: 157 | 158 | ```php 159 |

Hola , ¡Qué lindo es utilizar KumbiaPHP! ¿Cierto?

160 |

Fecha y hora actual:

161 | ``` 162 | 163 | Al ingresar en `http://127.0.0.1:8001/greetings/hello/CaChi/`, se mostrará un saludo personalizado junto con la fecha actual 164 | (figura 5). 165 | 166 | ![](../images/kumbiaphp-greetings-hello-cachi.png) 167 | *Figura 5: Saludando al usuario* 168 | 169 | > 💡 **Nota:** KumbiaPHP incluye la función h() como atajo de htmlspecialchars(). Se recomienda envolver los valores 170 | dinámicos en h() para evitar problemas de seguridad (XSS) y garantizar que se respete el charset de la aplicación. 171 | 172 | ## Añadiendo una nueva acción: goodbye() 173 | 174 | Hasta ahora hemos creado la acción `hello()` y su vista asociada. Para completar el ejemplo, vamos a añadir una segunda acción dentro del mismo controlador: `goodbye()`. 175 | Con esta nueva acción mostraremos cómo reutilizar la misma lógica aprendida (controlador + vista) pero en este caso para despedir al usuario en lugar de saludarlo. 176 | 177 | ```php 178 | date = date("Y-m-d H:i"); 193 | $this->name = $name; 194 | } 195 | 196 | /** 197 | * Farewell action 198 | * 199 | * @param string $name User name 200 | * @return void 201 | */ 202 | public function goodbye($name) 203 | { 204 | $this->name = $name; 205 | } 206 | } 207 | ``` 208 | 209 | Ahora creamos la vista `app/views/greetings/goodbye.phtml`: 210 | 211 | ```php 212 |

¡Adiós ! 👋

213 |

Esperamos verte pronto de nuevo.

214 | 215 | ``` 216 | 217 | Si accedemos a `http://127.0.0.1:8001/greetings/goodbye/CaChi`, veremos el mensaje de despedida con un enlace para volver a 218 | saludar (figura 6). 219 | 220 | ![](../images/kumbiaphp-greetings-goodbye.png) 221 | *Figura 6: Despedida al usuario* 222 | 223 | El método `Html::linkAction()` es un **helper** que facilita la creación de enlaces. En lugar de escribir manualmente: 224 | 225 | ```html 226 | Volver a saludar 227 | ``` 228 | 229 | ...lo hacemos de manera más limpia y mantenible. Así, si cambiamos el nombre del controller, no tendremos que modificar 230 | cada enlace manualmente. 231 | 232 | Con este primer ejemplo hemos aprendido a crear un controlador y sus vistas asociadas en KumbiaPHP, comprender cómo se estructuran las URLs y cómo se transmiten parámetros a las acciones. A través de un sencillo saludo y una despedida, se ilustra de forma práctica la arquitectura MVC, el paso de variables a las vistas y el uso de helpers que simplifican el código. Con estas bases, ya estamos listos para desarrollar aplicaciones más completas con KumbiaPHP. 233 | -------------------------------------------------------------------------------- /es/mvc.md: -------------------------------------------------------------------------------- 1 | # Modelo, Vista, Controlador (MVC) 2 | 3 | ## ¿Qué es MVC? 4 | 5 | En 1979, Trygve Reenskaug desarrolló una arquitectura para la creación de aplicaciones interactivas, compuesta por tres 6 | partes: modelos, vistas y controladores. El modelo MVC permite separar la capa de interfaz, el modelo de datos y la 7 | lógica de control. Este estilo de programación por capas ayuda a aislar la lógica de negocio de la presentación, lo 8 | cual, por ejemplo, evita mezclar la capa de datos con la capa de presentación. 9 | 10 | La principal ventaja de esta arquitectura es que el desarrollo se puede realizar en diferentes niveles, de manera que, 11 | si se requiere un cambio, solo se modifica la capa correspondiente, sin necesidad de examinar código mezclado. Además, 12 | facilita la distribución de tareas por niveles, de modo que cada equipo de trabajo se abstrae de los demás y solo 13 | necesita conocer la interfaz (API) que conecta las capas. Esta separación reduce la complejidad, promueve la 14 | reutilización y acelera el proceso de ensamblar, desensamblar o sustituir cualquier capa mientras mantenga la misma 15 | responsabilidad. 16 | 17 | En una aplicación web, la petición (generalmente vía HTTP) se envía al controlador. El controlador interactúa con el 18 | modelo según sea necesario y luego invoca la vista correspondiente. Esta vista obtiene el estado del modelo a través del 19 | controlador y lo muestra al usuario. 20 | 21 | ## ¿Cómo KumbiaPHP aplica el MVC? 22 | 23 | KumbiaPHP Framework aprovecha los mejores patrones de programación orientada a la Web, en especial el patrón MVC 24 | (Modelos, Vistas, Controladores). El objetivo es mantener separadas la lógica de la aplicación, los datos y la 25 | presentación. Esta separación ofrece ventajas muy importantes, como aislar rápidamente un problema según la capa donde 26 | se origine. Además, permite desarrollar múltiples formas de presentación sin duplicar la lógica de la aplicación. Cada 27 | parte funciona de manera independiente, y cualquier modificación se concentra en su propio componente sin afectar a 28 | otras partes de la aplicación. 29 | 30 | ## Más información 31 | 32 | KumbiaPHP se basa en MVC y POO, un patrón de diseño clásico que funciona en tres capas: 33 | 34 | - **Modelos:** Representan la información y la lógica de negocio de la aplicación. 35 | - **Vistas:** Se encargan de presentar la información al usuario (generalmente a través de páginas web), aunque pueden 36 | adoptar otros formatos como XML, PDF, JSON, etc. 37 | - **Controladores:** Responden a las acciones del usuario e invocan los cambios necesarios en los modelos o las vistas. 38 | 39 | En KumbiaPHP, los controladores se dividen en un front controller y en acciones específicas que saben cómo responder 40 | ante distintos tipos de peticiones. Las vistas se gestionan mediante templates, views y partials. El modelo proporciona 41 | una capa de abstracción de la base de datos, además de gestionar datos de sesión y validaciones de integridad 42 | relacional, separando la lógica de negocio (modelos) de la presentación (vistas). 43 | 44 | Por ejemplo, supongamos que deseas presentar la misma información de dos formas distintas: una vista HTML para uso en 45 | navegador y una vista que exporte los mismos datos en JSON (pensando en un servicio web o consumo por parte de otra 46 | aplicación). Ambas vistas pueden reutilizar el mismo controlador y modelo, variando únicamente la forma en que presentan 47 | la información. El controlador aísla la comunicación y los detalles del protocolo (HTTP, consola, etc.), mientras que el 48 | modelo abstrae la lógica de datos, haciéndolo independiente de la vista. Gracias a pequeñas convenciones, se puede 49 | obtener una gran potencia y flexibilidad. 50 | 51 | ## Caso práctico 52 | 53 | Para comprender mejor cómo funciona la arquitectura MVC en una tarea concreta, veremos un ejemplo para añadir un 54 | producto a un carrito de compras: 55 | 56 | 1. El Front Controller recibe la acción del usuario (por ejemplo, hacer clic en el botón “Agregar al carrito”) y, tras 57 | ejecutar algunas tareas (enrutamiento, seguridad, etc.), identifica que debe llamar a la acción `add` en el 58 | controlador. 59 | 2. La acción `add` accede al modelo y actualiza el objeto del carrito en la sesión del usuario. 60 | 3. Si se completa la modificación correctamente, la acción prepara los datos que se enviarán a la vista (confirmación de 61 | la adición y la lista completa de productos del carrito). La vista luego ensambla la respuesta, generando la página 62 | que muestra el carrito de compras. 63 | 4. Finalmente, la respuesta es transferida al servidor web, que la envía al usuario para que la lea y siga 64 | interactuando. 65 | 66 | A continuación, se presenta un ejemplo de implementación que ilustra este proceso. Ten en cuenta que, en un caso real, 67 | cada proyecto puede tener sus propias particularidades de lógica y organización de carpetas, pero la idea fundamental de 68 | MVC se mantiene. 69 | 70 | ### Ejemplo de código con MVC en KumbiaPHP 71 | 72 | #### Controlador: `controllers/cart_controller.php` 73 | ```php 74 | find_first($productId); 93 | 94 | // If product is found, add it to the cart 95 | if ($product) { 96 | // 'Cart' could be a model or a service handling cart operations 97 | Cart::addProduct($product); 98 | Flash::valid('Product added to cart successfully!'); 99 | } else { 100 | Flash::error('Product not found!'); 101 | } 102 | 103 | // Redirect or render the cart view 104 | Redirect::toAction('show'); 105 | } 106 | 107 | /** 108 | * Shows the current status of the cart. 109 | * 110 | * @return void 111 | */ 112 | public function show() 113 | { 114 | // Retrieve the cart contents from the Cart model or session 115 | $this->cartItems = Cart::getItems(); 116 | } 117 | } 118 | 119 | ``` 120 | 121 | #### Modelo: `models/cart.php` 122 | ```php 123 | $product->id, 150 | 'name' => $product->name, 151 | 'price' => $product->price 152 | ]; 153 | 154 | // Store the updated cart back into the session 155 | Session::set('cart', $cart, self::SESSION_NAMESPACE); 156 | } 157 | 158 | /** 159 | * Retrieves all items from the cart stored in the session. 160 | * 161 | */ 162 | public static function getItems(): array 163 | { 164 | 165 | // Get the cart items from the session 166 | return Session::get('cart', self::SESSION_NAMESPACE) ?? []; 167 | } 168 | } 169 | 170 | ``` 171 | 172 | #### Vista: `views/cart/show.phtml` 173 | ```html 174 | 175 |

My Shopping Cart

176 | 177 | 178 |

Your cart is empty.

179 | 180 | 181 | 182 | 189 | 190 | ``` 191 | 192 | En este ejemplo, cada capa (controlador, modelo y vista) cumple un rol definido: 193 | - El **controlador** recibe la petición y decide qué acciones tomar (`add` o `show`). 194 | - El **modelo** (en este caso, la clase `Cart`) encapsula la lógica de negocio para administrar los productos en el 195 | carrito. 196 | - La **vista** (`views/cart/show.phtml`) se encarga de presentar la información de manera adecuada al usuario. 197 | 198 | Así, se logra un código más ordenado, fácil de mantener y escalable. 199 | -------------------------------------------------------------------------------- /es/appendix.md: -------------------------------------------------------------------------------- 1 | # Apéndices 2 | 3 | ## Integración de jQuery y KumbiaPHP 4 | 5 | KumbiaPHP provee de una integración con el Framework de DOM en JavaScript, 6 | jQuery 7 | 8 | ### KDebug 9 | 10 | KDebug es un nuevo objeto incorporado al plugins de integración 11 | KumbiaPHP/jQuery que permite una depuración del código en tiempo de 12 | desarrollo. Con solo un parámetro se puede aplicar un log que permite ver en 13 | consola (mientras esta este disponible, sino usara alert) que permite un 14 | mejor control de la ejecución. 15 | 16 | No es necesario pero si recomendable usar Firebug si se trabaja en Mozilla 17 | Firefox o algún navegador que use la consola de WebKit como Google Chrome. 18 | 19 | 20 | 21 | ## Aplicación en producción 22 | 23 | TODO 24 | 25 | ## Partials de paginación 26 | 27 | Como complemento para el paginado de ActiveRecord, a través de vistas 28 | parciales se implementan los tipos de pacciona mas comunes. Estos se ubican 29 | en el directorio "core/views/partials/paginators" listos para ser usados. Son 30 | completamente configurables vía CSS. Por supuesto, podéis crear vuestros 31 | propios partials para paginar en las vistas. 32 | 33 | ### Classic 34 | 35 | Vista de paginado clásica. 36 | 37 | ![](../images/image07.jpg) 38 | 39 | Resultado Final 40 | 41 | Parámetros de configuración: 42 | 43 | page: objeto obtenido al invocar al paginador. 44 | 45 | show: número de páginas que se mostraran en el paginador, por defecto 10. 46 | 47 | url: url para la accion que efectúa la pacciona, por defecto 48 | "module/controller/page/" y se envía por parámetro el número de página. 49 | 50 | ```php 51 | View::partial('paginators/classic', false, array ( 'page' => $page, 'show' => 8, 'url' => 'usuario/lista')); 52 | ``` 53 | 54 | --- 55 | 56 | ### Digg 57 | 58 | Vista de paginación estilo digg. 59 | 60 | Parámetros de configuración: 61 | 62 | page: objeto obtenido al invocar al paginador. 63 | 64 | show: número de páginas que muestra el paginador, por defecto 10. 65 | 66 | url: url para la accion que efectúa la pacciona , por defecto 67 | "module/controller/page/" y se envía por parámetro el número de página. 68 | 69 | ```php 70 | View::partial('paginators/digg', false, array('page' => $page, 'show' => 8, 'url' => 'usuario/lista')); 71 | ``` 72 | 73 | --- 74 | 75 | ### Extended 76 | 77 | ![](../images/image00.jpg) 78 | 79 | Resultado Final 80 | 81 | Vista de paginación extendida. 82 | 83 | Parámetros de configuración: 84 | 85 | page: objeto obtenido al invocar al paginador. 86 | 87 | url: url para la accion que efectúa la pacciona , por defecto 88 | "module/controller/page/" y se envía por parámetro el número de página. 89 | 90 | ```php 91 | View::partial('paginators/extended', false, array('page' => $page, 'url' => 'usuario/lista')); 92 | ``` 93 | 94 | --- 95 | 96 | ### Punbb 97 | 98 | Vista de paginación estilo punbb. 99 | 100 | Parámetros de configuración: 101 | 102 | page: objeto obtenido al invocar al paginador. 103 | 104 | show: número de páginas que muestra el paginador, por defecto 10. 105 | 106 | url: url para la acción que efectúa la paginación, por defecto 107 | "module/controller/page/" y se envia por parámetro el número de página. 108 | 109 | ```php 110 | View::partial('paginators/punbb', false, array('page' => $page, 'show' => 8, 'url' => 'usuario/lista')); 111 | ``` 112 | 113 | --- 114 | 115 | ### Simple 116 | 117 | ![](../images/image11.jpg) 118 | 119 | Resultado Final 120 | 121 | Vista de paginación simple. 122 | 123 | Parámetros de configuración: 124 | 125 | page: objeto obtenido al invocar al paginador. 126 | 127 | url: url para la acción que efectua la paginación , por defecto 128 | "module/controller/page/" y se envía por parámetro el número de página. 129 | 130 | ```php 131 | View::partial('paginators/simple', false, array('page' => $page, 'url' => 'usuario/lista')); 132 | ``` 133 | 134 | --- 135 | 136 | ### Ejemplo de uso 137 | 138 | Supongamos que queremos paginar una lista de usuarios. 139 | 140 | Para el modelo Usuario en models/usuario.php: 141 | ```php 142 | paginate("page: $page", 'per_page: 5'); 154 | } 155 | } 156 | 157 | ``` 158 | 159 | Para el controlador UsuarioController en controllers/usuario_controller.php: 160 | 161 | ```php 162 | page = (new Usuario)->ver($page); 175 | } 176 | } 177 | 178 | ``` 179 | 180 | Y en la vista views/usuario/page.phtml 181 | 182 | ```php 183 | 184 | 185 | 186 | 187 | 188 | items as $p) : ?> 189 | 190 | 191 | 192 | 193 | 194 |
IdNombre
id ?>nombre ?>
195 | 196 | $page]) ?> 197 | ``` 198 | 199 | --- 200 | 201 | * * * 202 | 203 | ## Auth 204 | 205 | * * * 206 | 207 | ## Beta1 a Beta2 208 | 209 | * * * 210 | 211 | ## Deprecated 212 | 213 | ## Métodos y clases que se usaban en versiones anteriores y que aun 214 | funcionan. Pero que quedan desaconsejadas y que no funcionarán en el futuro 215 | (próxima beta o versión final): 216 | 217 | Posiblemente habrá 2 versiones: 218 | 219 | 0.9 = 100% compatible beta2, con lo deprecated para facilitar migración 220 | 221 | 1.0 = sin lo deprecated más limpia y rápida, para empezar nuevas apps 222 | 223 | 0.5 | beta1 | beta2 v0.9 | v1.0 224 | --- | ----- | ---------- | ---- 225 | 226 | Flash::success() ahora Flash::valid() 227 | 228 | Flash::notice() ahora Flash::info() 229 | 230 | ApplicationController ahora AppController (con sus respectivos cambios de 231 | metodos) 232 | 233 | …. 234 | 235 | Usar $this->response = 'view' o View::response('view') para no mostrar el 236 | template. 237 | 238 | Ahora View::template(NULL) el View::response() solo se usa para elegir 239 | formatos de vista alternativos. 240 | 241 | ### Lista de cambios entre versiones: si no se especifica beta1 es que es 242 | compatible en ambos casos 243 | 244 | #### Application 245 | 246 | 0.5 | beta1 | beta2 v0.9 | v1.0 247 | --- | ----- | ---------- | ---- 248 | ControllerBase | ApplicationController | AppController | AppController 249 | public function init() | protected function initialize() |protected function initialize() | protected function initialize() 250 | render_view() | render_view() | View::select() | View::select() 251 | 252 | 253 | 254 | #### Models 255 | 256 | 0.5 | beta1 | beta2 v0.9 | v1.0 257 | --- | ----- | ---------- | ---- 258 | public $mode | public $database | public $database |public $database 259 | 260 | #### Callbacks 261 | 262 | 0.5 | beta1 | beta2 v0.9 | v1.0 263 | --- | ----- | ---------- | ---- 264 | public function init() | protected function initialize() | protected function initialize() | protected function initialize() 265 | public function finalize() | | protected function finalize() | protected function finalize() 266 | public function before_filter()| | protected function before_filter() | protected function before_filter() 267 | public function after_filter() | | protected function after_filter() | protected function after_filter() 268 | 269 | boot.ini se elimina en beta2 270 | 271 | kumbia / mail / libchart 0.5 => se elimina los prefijos beta1 272 | 273 | extensions 0.5 => libs beta1 274 | 275 | Input:: 276 | 277 | $this->has_post 0.5 => Input::hasPost beta2 278 | 279 | $this->has_get 0.5 => Input::hasGet beta2 280 | 281 | $this->has_request 0.5 => Input::hasRequest beta2 282 | 283 | $this->post 0.5 => 'Input::post beta2 284 | 285 | $this->get 0.5 => 'Input::get beta2 286 | 287 | $this->request 0.5 => 'Input::request beta2 288 | 289 | View:: 290 | 291 | $this->cache 0.5 => View::cache beta2 292 | 293 | $this->render 0.5 => 'View::select beta2 294 | 295 | $this->set_response 0.5 => View::response beta2 296 | 297 | content() 0.5 => View::content() beta2 298 | 299 | render_partial 0.5 => View::partial beta2 300 | 301 | Router:: 302 | 303 | $this->route_to 0.5 => 'Router::route_to beta1 y beta2 304 | 305 | $this->redirect 0.5 => Router::redirect beta2 306 | 307 | Html:: 308 | 309 | img_tag 0.5 => 'Html::img beta2 310 | 311 | link_to 0.5 => 'Html::link beta2 312 | 313 | link_to_action 0.5 => 'Html::linkAction beta2 314 | 315 | stylesheet_link_tags 0.5 => 'Html::includeCss beta2 316 | 317 | Ajax:: 318 | 319 | form_remote_tag 0.5 => 'Ajax::form beta2 320 | 321 | link_to_remote 0.5 => 'Ajax::link beta2 322 | 323 | Form:: 324 | 325 | end_form_tag 0.5 => 'Form::close beta2 326 | 327 | form_tag 0.5 => 'Form::open beta2 328 | 329 | input_field_tag 0.5 ' => 'Form::input beta2 330 | 331 | text_field_tag 0.5 => 'Form::text beta2 332 | 333 | password_field_tag 0.5 => 'Form::pass beta2 334 | 335 | textarea_tag 0.5 => 'Form::textarea beta2 336 | 337 | hidden_field_tag 0.5 => 'Form::hidden beta2 338 | 339 | select_tag 0.5 => 'Form::select beta2 340 | 341 | file_field_tag 0.5 => 'Form::file beta2 342 | 343 | button_tag 0.5 => 'Form::button beta2 344 | 345 | submit_image_tag 0.5 => 'Form::submitImage beta2 346 | 347 | submit_tag 0.5 => 'Form::submit beta2 348 | 349 | checkbox_field_tag 0.5 => 'Form::check beta2 350 | 351 | radio_field_tag 0.5 => 'Form::radio beta2 352 | 353 | Tag:: 354 | 355 | javascript_include_tag 0.5 => 'Tag::js beta2 356 | 357 | stylesheet_link_tag 0.5 => 'Tag::css beta2 358 | 359 | ### Cambio en las rutas entre versiones: 360 | 361 | # 0.5 => 1.0 beta1 362 | 363 | '/apps/default' => '/app', 364 | 365 | '/apps' => '', 366 | 367 | '/app/controllers/application.php' => '/app/application.php', 368 | 369 | '/app/views/layouts' => '/app/views/templates', 370 | 371 | '/app/views/index.phtml' => '/app/views/templates/default.phtml', 372 | 373 | '/app/views/not_found.phtml' => '/app/views/errors/404.phtml', 374 | 375 | '/app/views/bienvenida.phtml' => '/app/views/pages/index.phtml', 376 | 377 | '/app/helpers' => '/app/extensions/helpers', 378 | 379 | '/app/models/base/model_base.php' => '/app/model_base.php', 380 | 381 | '/app/models/base/' => '', 382 | 383 | '/cache' => '/app/cache', 384 | 385 | '/config' => '/app/config', 386 | 387 | '/docs' => '/app/docs', 388 | 389 | '/logs' => '/app/logs', 390 | 391 | '/scripts' => '/app/scripts', 392 | 393 | '/test' => '/app/test', 394 | 395 | # 1.0 beta1 => 1.0 beta2 396 | 397 | … 398 | 399 | Cambiados: 400 | 401 | Session::isset_data() ahora Session::has() 402 | 403 | Session::unset_data() ahora Session::delete() 404 | 405 | * * * 406 | 407 | ## Glosario 408 | 409 | CRUD = Create Read Update Delete ( Crear Leer Actualizar Borrar ) 410 | 411 | ABM 412 | 413 | MVC = Model View Controller ( Modelo Vista Controlador ) 414 | 415 | HTML = HyperText Markup Language ( Lenguaje de Marcado de HiperTexto ) 416 | 417 | SQL = Structured Query Language ( Lenguaje de Consulta Estructurado ) 418 | -------------------------------------------------------------------------------- /en/appendix.md: -------------------------------------------------------------------------------- 1 | # Appendices 2 | 3 | ## Integration of jQuery and KumbiaPHP 4 | 5 | KumbiaPHP provides integration with the JavaScript Framework jQuery 6 | 7 | ### KDebug 8 | 9 | KDebug is a new object incorporated to the integration plugins at KumbiaPHP/JQuery that allows a debugging of the code in development time. With just one parameter you can use a log that allow see in console (while available, if not it using alert) allowing a better control of the execution. 10 | 11 | It's not necessary, but will be helpful if you work with tools like Firebug in Mozilla Firefox o some browser that use the WebKit console, like Google Chrome. 12 | 13 | ## Application in production 14 | 15 | All 16 | 17 | ## Partials of paging 18 | 19 | As complement to the ActiveRecord, paged through partial views are implemented types of pacciona more common. These are located in the directory "core/views/partials/paginators" ready to be used. They are fully configurable via CSS. Of course, you can create your own partials for pagination in views. 20 | 21 | ### Classic 22 | 23 | Classic pagination view 24 | 25 | ![](../images/image07.jpg) 26 | 27 | Final result 28 | 29 | Configuration parameters: 30 | 31 | page: object obtained from paginator. 32 | 33 | show: number of pages to be shown in the paginator. Default 10. 34 | 35 | url: URL for the action that performs pagination it, by default "module/controller/page /" and the page number is sent by parameter. 36 | 37 | ```php 38 | View::partial('paginators/classic', false, array ( 'page' => $page, 'show' => 8, 'url' => 'user/list')); 39 | ``` 40 | 41 | * * * 42 | 43 | ### Digg 44 | 45 | View paging style digg. 46 | 47 | Configuration parameters: 48 | 49 | page: object obtained from paginator. 50 | 51 | show: number of pages to be shown in the paginator. Default 10. 52 | 53 | URL: url for the action that performs pagination it, by default "module/controller/page /" and the page number is sent by parameter. 54 | 55 | ```php 56 | View:partial (' paginators/digg', false, array('page' => $page, 'show' => 8, 'url' => 'usuario/lista')); 57 | ``` 58 | 59 | * * * 60 | 61 | ### Extended 62 | 63 | ![](../images/image00.jpg) 64 | 65 | Final result 66 | 67 | Classic's file pagination view. 68 | 69 | Configuration parameters: 70 | 71 | page: object obtained from paginator. 72 | 73 | url: url for the action that performs pacciona it, by default "module/controller/page /" and the page number is sent by parameter. 74 | 75 | ```php 76 | View::partial('paginators/extended', false, array('page' => $page, 'url' => 'user/list')); 77 | ``` 78 | 79 | * * * 80 | 81 | ### Punbb 82 | 83 | View paging style punbb. 84 | 85 | Configuration parameters: 86 | 87 | page: object obtained from paginator. 88 | 89 | show: number of pages to be shown in the paginator. Default 10. 90 | 91 | url: URL for the action that performs pagination it, by default "module/controller/page /" and the page number is sent by parameter. 92 | 93 | ```php 94 | View::partial('paginators/punbb', false, array('page' => $page, 'show' => 8, 'url' => 'user/list')); 95 | ``` 96 | 97 | * * * 98 | 99 | ### Simple 100 | 101 | ![](../images/image11.jpg) 102 | 103 | Final result 104 | 105 | View paging style simple. 106 | 107 | Configuration parameters: 108 | 109 | page: object obtained from paginator. 110 | 111 | url: URL for the action that performs pagination it, by default "module/controller/page /" and the page number is sent by parameter. 112 | 113 | ```php 114 | View::partial('paginators/simple', false, array('page' => $page, 'url' => 'user/list')); 115 | ``` 116 | 117 | * * * 118 | 119 | ### Sample Usage 120 | 121 | Suppose we want to paginate a list of users. 122 | 123 | For model User in "models/user.php": 124 | 125 | ```php 126 | paginate("page: $page", 'per_page: 5'); 138 | } 139 | } 140 | 141 | ``` 142 | 143 | For the UserController controller in "controllers/usuario_controller. php": 144 | 145 | ```php 146 | page = (new Usuario)->displayUsers($page); 159 | } 160 | } 161 | 162 | ``` 163 | 164 | And in the view "views/user/page.phtml" 165 | 166 | ```php 167 | 168 | 169 | 170 | 171 | 172 | items as $p) : ?> 173 | 174 | 175 | 176 | 177 | 178 |
IdName
id ?>name ?>
179 | 180 | $page]) ?> 181 | ``` 182 | 183 | * * * 184 | 185 | * * * 186 | 187 | ## Auth 188 | 189 | * * * 190 | 191 | ## Beta1 to Beta2 192 | 193 | * * * 194 | 195 | ## Deprecated 196 | 197 | ## Methods and classes that were used in previous versions and still work 198 | 199 | But they are deprecated and will not work in the future (next beta or final release): 200 | 201 | Possibly there will be 2 versions: 202 | 203 | Compatible with beta2, supports deprecated to facilitate migration 204 | 205 | 1.0 = without the deprecated more clean and fast, to start new apps 206 | 207 | | 0.5 | beta1 | beta2 v0.9 | v1.0 | 208 | | --- | ----- | ---------- | ---- | 209 | | | | | | 210 | 211 | Flash::success() now is Flash::valid() 212 | 213 | Flash::notice() now is Flash::info() 214 | 215 | ApplicationController now is AppController (with their respective method changes) 216 | 217 | ... 218 | 219 | Use $this->response = 'view' or View:response('view') to not show the template. 220 | 221 | Now, View::template (NULL) or View::response() is used to choose alternative view formats. 222 | 223 | ### List of changes between versions: If don't specify beta1 is that it is compatible in both cases 224 | 225 | 226 | 227 | #### Application 228 | 229 | | 0.5 | beta1 | beta2 v0.9 | v1.0 | 230 | | ---------------------- | ------------------------------- | ------------------------------- | ------------------------------- | 231 | | ControllerBase | ApplicationController | AppController | AppController | 232 | | public function init() | protected function initialize() | protected function initialize() | protected function initialize() | 233 | | render_view() | render_view() | View::select() | View::select() | 234 | 235 | #### Models 236 | 237 | | 0.5 | beta1 | beta2 v0.9 | v1.0 | 238 | | ------------ | ---------------- | ---------------- | ---------------- | 239 | | public $mode | public $database | public $database | public $database | 240 | 241 | #### Callbacks 242 | 243 | | 0.5 | beta1 | beta2 v0.9 | v1.0 | 244 | | ------------------------------- | ------------------------------- | ---------------------------------- | ---------------------------------- | 245 | | public function init() | protected function initialize() | protected function initialize() | protected function initialize() | 246 | | public function finalize() | | protected function finalize() | protected function finalize() | 247 | | public function before_filter() | | protected function before_filter() | protected function before_filter() | 248 | | public function after_filter() | | protected function after_filter() | protected function after_filter() | 249 | 250 | boot.ini is eliminated in beta2 251 | 252 | kumbia / mail / libchart 0.5 => deletes the prefixes beta1 253 | 254 | extensions 0.5 => libs beta1 255 | 256 | Input:: 257 | 258 | $this->has_post 0.5 => Input:hasPost beta2 259 | 260 | $this->has_get 0.5 => Input:hasGet beta2 261 | 262 | $this->has_request 0.5 => Input:hasRequest beta2 263 | 264 | $this->post 0.5 => ' Input:post beta2 265 | 266 | $this->get 0.5 => ' Input:get beta2 267 | 268 | $this->request 0.5 => 'Input::request beta2 269 | 270 | View:: 271 | 272 | $this->cache 0.5 => View::cache beta2 273 | 274 | $this->render 0.5 => 'View::select beta2 275 | 276 | $this->set_response 0.5 => View::response beta2 277 | 278 | content() 0.5 => View::content() beta2 279 | 280 | render_partial 0.5 => View::partial beta2 281 | 282 | Router:: 283 | 284 | $this->route_to 0.5 => 'Router::route_to beta1 y beta2 285 | 286 | $this->redirect 0.5 => Router::redirect beta2 287 | 288 | Html:: 289 | 290 | img_tag 0.5 => 'Html::img beta2 291 | 292 | link_to 0.5 => 'Html::link beta2 293 | 294 | link_to_action 0.5 => 'Html::linkAction beta2 295 | 296 | stylesheet_link_tags 0.5 => 'Html::includeCss beta2 297 | 298 | Ajax:: 299 | 300 | form_remote_tag 0.5 => 'Ajax::form beta2 301 | 302 | link_to_remote 0.5 => 'Ajax::link beta2 303 | 304 | Form:: 305 | 306 | end_form_tag 0.5 => 'Form::close beta2 307 | 308 | form_tag 0.5 => 'Form::open beta2 309 | 310 | input_field_tag 0.5 ' => 'Form::input beta2 311 | 312 | text_field_tag 0.5 => 'Form::text beta2 313 | 314 | password_field_tag 0.5 => 'Form::pass beta2 315 | 316 | textarea_tag 0.5 => 'Form::textarea beta2 317 | 318 | hidden_field_tag 0.5 => 'Form::hidden beta2 319 | 320 | select_tag 0.5 => 'Form::select beta2 321 | 322 | file_field_tag 0.5 => 'Form::file beta2 323 | 324 | button_tag 0.5 => 'Form::button beta2 325 | 326 | submit_image_tag 0.5 => 'Form::submitImage beta2 327 | 328 | submit_tag 0.5 => 'Form::submit beta2 329 | 330 | checkbox_field_tag 0.5 => 'Form::check beta2 331 | 332 | radio_field_tag 0.5 => 'Form::radio beta2 333 | 334 | Tag:: 335 | 336 | javascript_include_tag 0.5 => 'Tag::js beta2 337 | 338 | stylesheet_link_tag 0.5 => 'Tag::css beta2 339 | 340 | ### Change on routes between versions: 341 | 342 | # 0.5 => 1.0 beta1 343 | 344 | '/apps/default' => '/app', 345 | 346 | '/apps' => '', 347 | 348 | '/app/controllers/application.php' => '/app/application.php', 349 | 350 | '/app/views/layouts' => '/app/views/templates', 351 | 352 | '/app/views/index.phtml' => '/app/views/templates/default.phtml', 353 | 354 | '/app/views/not_found.phtml' => '/app/views/errors/404.phtml', 355 | 356 | '/app/views/bienvenida.phtml' => '/app/views/pages/index.phtml', 357 | 358 | '/app/helpers' => '/app/extensions/helpers', 359 | 360 | '/app/models/base/model_base.php' => '/app/model_base.php', 361 | 362 | '/app/models/base/' => '', 363 | 364 | '/cache' => '/app/cache', 365 | 366 | '/config' => '/app/config', 367 | 368 | '/docs' => '/app/docs', 369 | 370 | '/logs' => '/app/logs', 371 | 372 | '/scripts' => '/app/scripts', 373 | 374 | '/test' => '/app/test', 375 | 376 | 377 | # 1.0 beta1 => 1.0 beta2 378 | 379 | … 380 | 381 | 382 | Changed: 383 | 384 | Session::isset_data() ahora Session::has() 385 | 386 | Session::unset_data() ahora Session::delete() 387 | 388 | * * * 389 | 390 | ## Glossary 391 | 392 | CRUD = Create Read Update Delete 393 | 394 | ABM 395 | 396 | MVC = Model View Controller 397 | 398 | HTML = HyperText Markup Language 399 | 400 | SQL = Structured Query Language -------------------------------------------------------------------------------- /es/controller.md: -------------------------------------------------------------------------------- 1 | # El Controlador 2 | 3 | En **KumbiaPHP Framework**, la *capa del controlador* es el puente que conecta la lógica de negocio con la presentación. 4 | Se compone de varios elementos clave: 5 | 6 | * **Acciones**: verifican la integridad de las peticiones y preparan los datos que la vista necesita. 7 | * **Clases auxiliares (`Input`, `Session`, etc.)**: facilitan el acceso a parámetros de la petición y a datos 8 | persistentes del usuario. 9 | * **Filtros**: fragmentos de código que se ejecutan antes y/o después de un controlador o de una acción para realizar 10 | validaciones, aplicar reglas de seguridad, modificar la respuesta, etc. 11 | 12 | En una página sencilla, bastará con un par de líneas en la acción que corresponda. El resto de componentes se usan 13 | cuando el escenario lo requiere. 14 | 15 | ## Las Acciones 16 | 17 | Las acciones constituyen el flujo básico de la aplicación: reciben la petición, interactúan con el modelo y definen 18 | variables para la vista. Cuando llega una URL, KumbiaPHP determina qué acción ejecutar y qué parámetros entregar. 19 | Consulta la sección [KumbiaPHP y sus URLs](first-app.md#kumbiaphp-y-sus-urls) para más detalles. 20 | 21 | Las acciones son métodos dentro de un *ClassController* que hereda de **`AppController`**; estos controladores pueden 22 | estar organizados o no en módulos. 23 | 24 | ### Acciones y vistas 25 | 26 | Por convención, al terminar una acción KumbiaPHP busca una vista con el mismo nombre. Si existe una acción `hello()`, 27 | debe existir una vista `hello.phtml`. (En capítulos posteriores profundizaremos en el sistema de vistas). 28 | 29 | ### Obtener valores desde una acción 30 | 31 | Las URL de KumbiaPHP siguen una estructura predecible. Desde el controlador puedes acceder a los valores recibidos 32 | mediante propiedades públicas: 33 | 34 | * `controller_name` 35 | * `action_name` 36 | * `parameters` 37 | 38 | Ejemplo con la URL `http://127.0.0.1:8001/news/show/12/`: 39 | 40 | ```php 41 | controller_name; // news 55 | $this->action_name; // show 56 | $this->parameters; // Arreglo con todos los parámetro enviados a la acción 57 | } 58 | } 59 | ``` 60 | 61 | ### Validación automática del número de parámetros 62 | 63 | KumbiaPHP impide, por defecto, que se pasen más parámetros de los declarados en la firma del método. Si se invoca 64 | `show()` sin `$id` o con parámetros extra, el framework lanzará una excepción (en producción retornará *404*). 65 | 66 | #### Ejemplo de excepción por número de parámetros 67 | 68 | ```php 69 | name = $name; 83 | $this->date = date("Y-m-d H:i"); 84 | } 85 | } 86 | ``` 87 | 88 | Si accedes a `http://127.0.0.1:8001/greeting/hello/CaChi/param2/`, KumbiaPHP mostrará una excepción como la siguiente: 89 | 90 | ![Figura 1 – Excepción por número de parámetros](../images/incorrect-number-of-parameters.jpg) 91 | 92 | #### Permitir parámetros adicionales con `$limit_params` 93 | 94 | Para omitir la restricción de cantidad de parámetros en una acción (o en todo el controlador), declara la propiedad 95 | º`$limit_params` en **`false`**: 96 | 97 | ```php 98 | name = $name; 117 | $this->date = date("Y-m-d H:i"); 118 | } 119 | } 120 | ``` 121 | 122 | Prueba la URL `http://127.0.0.1:8001/greeting/hello/CaChi/param2/param3/`: verás la vista renderizada sin errores. 123 | 124 | ![Figura 2 – Parámetros adicionales admitidos](../images/bypass-incorrect-number-of-parameters.jpg) 125 | 126 | ## Convenciones y creación de un Controlador 127 | 128 | ### Convenciones 129 | 130 | * Los controladores se guardan en **`app/controllers/`**. 131 | * El archivo termina en `_controller.php` (`greeting_controller.php`). 132 | * El nombre de la clase sigue la notación *CamelCase* (`GreetingController`). 133 | 134 | ### Creación de un Controlador mínimo 135 | 136 | ```php 137 | **Nota:** Próximas versiones del framework incluirán una implementación básica de autenticación para esta clase. 158 | 159 | ## Filtros 160 | 161 | Los filtros permiten ejecutar lógica adicional antes o después de un controlador o de una acción. Son especialmente 162 | útiles para validar solicitudes AJAX, cambiar el formato de la respuesta, limpiar datos de sesión, etc. 163 | 164 | ### Filtros de Controlador 165 | 166 | Se ejecutan antes y después de un **controlador completo**. 167 | Ejemplos de uso: validar acceso a un módulo, verificar sesiones de usuario, bloquear controladores no autorizados. 168 | 169 | * **initialize()**: se ejecuta antes de cargar el controlador. 170 | * **finalize()**: se ejecuta después de procesar el controlador. 171 | 172 | Ambos métodos se sobrescriben en `AppController`. 173 | 174 | ### Filtros de Acción 175 | 176 | Se ejecutan antes y después de una **acción específica**. 177 | 178 | * **before\_filter()**: se ejecuta antes de la acción. Útil para validar si la petición es AJAX, entre otros. 179 | * **after\_filter()**: se ejecuta después de la acción. Se usa, por ejemplo, para modificar variables de sesión. 180 | 181 | ## Acciones y controladores por defecto 182 | 183 | En **KumbiaPHP** si la URL no especifica controlador ni acción, el *dispatcher* invoca por defecto al 184 | **`IndexController`** y a la acción **`index`**. 185 | Pero, ¿qué sucede cuando la URL *sí* indica un controlador existente y, a su vez, una **acción que no está declarada** 186 | en él? 187 | Por defecto el framework lanzaría un error *404*, pero podemos interceptar esta situación y ofrecer un comportamiento 188 | más flexible mediante el método mágico **`__call()`** de PHP. 189 | 190 | `__call()` se ejecuta automáticamente cuando se invoca un método inexistente o no accesible sobre un objeto. 191 | Al sobrescribirlo en un controlador, obtenemos la oportunidad de decidir qué hacer antes de que KumbiaPHP entregue un 192 | error al usuario. 193 | Esto abre varias posibilidades, por ejemplo: 194 | 195 | * Renderizar **vistas estáticas** sin crear acciones vacías. 196 | * Servir **páginas dinámicas** almacenadas en base de datos basándose en un *slug* presente en la URL. 197 | * Personalizar el manejo de errores 404 manteniendo la lógica dentro del propio controlador. 198 | 199 | A continuación se muestran dos patrones frecuentes que aprovechan `__call()` en proyectos reales. 200 | 201 | ### Controladores con `__call()` para vistas dinámicas 202 | 203 | Un escenario típico es el de un sitio de ayuda o documentación donde cada página corresponde a un archivo `.phtml` 204 | dentro de `app/views/pages/`. 205 | En lugar de definir docenas de métodos vacíos en un controlador, podemos cargar la vista que coincida con la acción 206 | solicitada. Un gran ejemplo de esto ya se encuentra disponible por defecto dentro de KumbiaPHP 207 | 208 | ```php 209 | slugShow($name, $args); 254 | } 255 | 256 | /** 257 | * Muestra la lista de artículos del blog. 258 | * 259 | * @return void 260 | */ 261 | public function index(): void 262 | { 263 | $this->articles = (new Articles)->all(); 264 | } 265 | 266 | /** 267 | * Encuentra el artículo por su slug y muestra la vista correspondiente. 268 | * 269 | * @param string $slug Slug de la entrada del blog 270 | * @param array $args Parámetros adicionales (no utilizados) 271 | * 272 | * @return void 273 | */ 274 | private function slugShow(string $slug, array $args): void 275 | { 276 | $this->article = (new Articles)->getBySlug($slug); 277 | 278 | View::select('slugShow'); 279 | } 280 | } 281 | ``` 282 | 283 | #### Vista genérica `app/views/blog/slugShow.phtml` 284 | 285 | ```php 286 | if (!$article) { 287 | View::partial('articles/404'); 288 | return 1; 289 | } 290 | 291 |

title) ?>

292 |
293 | content, '


295 | ``` 296 | 297 | Con esta configuración, cualquier URL `/blog/` funciona sin crear métodos adicionales: 298 | 299 | * `/blog/buscador-avanzado-texto-completo-kumbiaphp-meilisearch` → busca 300 | `slug = 'buscador-avanzado-texto-completo-kumbiaphp-meilisearch'` en la tabla **articles** y muestra el contenido. 301 | * `/blog/optimizando-la-renderizacion-condicional-en-vistas-de-kumbiaphp-con-return-1` → idéntico flujo con un solo 302 | archivo de vista. 303 | 304 | ![Figura 3 – Vista de ejemplo del blog](../images/kmbiaphp-blog-example-using-call.jpg) 305 | 306 | Si la página no existe, el mismo controlador mostrará un mensaje y podrá devolver un 404 personalizado. 307 | 308 | Con estos patrones, `__call()` se convierte en una herramienta poderosa para mantener controladores delgados y flexibles 309 | dentro de la arquitectura MVC de KumbiaPHP, evitando duplicación de código y mejorando la capacidad de extensión del 310 | proyecto. 311 | -------------------------------------------------------------------------------- /en/parent-class.md: -------------------------------------------------------------------------------- 1 | # Parent classes 2 | 3 | ## AppController 4 | 5 | ## View 6 | 7 | ... 8 | 9 | # Libs of KumbiaPHP 10 | 11 | Kumbiaphp have ready-to-use classes, but remember that you can create your own classes to reuse them in your projects. You can also use external KumbiaPHP classes, as explained in the next chapter. 12 | 13 | ## Cache 14 | 15 | A cache is a set of duplicate data of other originals, with the property that the original data are costly to access, usually in time, with respect to the copy in the cache. 16 | 17 | The cache data is implemented in KumbiaPHP using factory and singleton design patterns. To make use of the cache, it is necessary to have write permissions in the "cache" directory (only in the case of the handlers "sqlite" and "file"). 18 | 19 | Each cache is controlled by a cache handler. The system cache KumbiaPHP has currently the following handlers: 20 | 21 | * APC: use Alternative PHP Cache. 22 | * file: cache files, these are stored in the directory cache and compatible with all operating systems. 23 | * nixfile: cache files, these are stored in the directory cache and compatible only with operating systems \*nix (linux, freebsd, and others). This cache is more fast cache «file». 24 | * sqlite: cache using SqLite database and this is located in the cache directory. 25 | 26 | To obtain a cache handler you must use the method «driver» which provides the Cache class. 27 | 28 | ### driver($driver=null) 29 | 30 | This method allows to obtain a cache handler specific (APC, file, nixfile, sqlite, memsqlite). If not indicated, gets cache handler by default indicated in the config.ini. 31 | 32 | get ( 'data' ); // manejador para memcache $data_memcache = Cache:: driver ( 'memcache' )-> get ( 'data' ); // manejador para cache con APC $data_apc = Cache:: driver ( 'APC' )-> get ( 'data' ); \--- ### get($id, $group='default') Permite obtener un valor almacenado en la cache; es necesario especificar el parámetro $id con el "id" correspondiente al valor en cache, tomando de manera predeterminada el grupo "default". ### save($value, $lifetime=null, $id=false, $group='default') Permite guardar un valor en la cache, el tiempo de vida del valor en cache se debe especificar utilizando el formato de la funcion \[strtotime\](http://www.go ogle.com/url?q=http%3A%2F%2Fphp.net%2Fmanual%2Fes%2Ffunction.strtotime.php&sa= D&sntz=1&usg=AFQjCNH8Gfguulpd1VXJunl_FfDbd4Mc8w) de php. Al omitir parámetros al invocar el método save se comporta de la manera siguiente: * Si no se especifica $lifetime , entonces se cachea por tiempo indefinido. * Si no se especifica $id y $group , entonces se toma los indicados al invocar por última vez el método get . 35 | 36 | get('saludo'); if(!$data) { Cache::driver()->save('Hola', '+1 day'); } echo $data; \--- ### start ($lifetime, $id, $group='default') Muestra buffer de salida cacheado, o en caso contrario inicia cacheo de buffer de salida hasta que se invoque el método end. Este método se utiliza frecuentemente para cachear un fragmento de vista. 39 | 40 | start('+1 day', 'saludo')): ?> 41 | 42 | Hello end()? > 43 | 44 | 45 | 46 | 47 | * * * 48 | 49 | ### end ($save = true) 50 | 51 | End caching output buffer indicating if it should be kept or not in the cache. 52 | 53 | * * * 54 | 55 | ## Logger 56 | 57 | The Logger class for handling \[Log\] (http://www.google.com/url?q=http%3A%2F %2Fes.wikipedia.org%2Fwiki%2FLog_\(registro\) & sa = D & sntz = 1 & usg = AFQjCNGft16YEbrl ayLoKbZFpNDBDXgXAA) was rewritten statically, this means no longer necessary to create an instance of the Logger class. This class offers a variety of methods to handle different types of Log. 58 | 59 | 60 | 61 | * * * 62 | 63 | The previous statement will output the following: 64 | 65 | \[Thu, 05 Feb 09 15:19:39-0500\]\[ERROR\] Error message 66 | 67 | By default the log files have the name logDDMMYYY.txt this name can be changed if we so wish it through an additional parameter to the method. 68 | 69 | 70 | 71 | * * * 72 | 73 | You can see the second parameter now the file will be named mi_log.txt 74 | 75 | ### Logger:warning ($msg); 76 | 77 | ### Logger:error ($msg) 78 | 79 | ### Logger:debug ($msg) 80 | 81 | ### Logger:alert ($msg) 82 | 83 | ### Logger: critical ($msg) 84 | 85 | ### Logger:notice ($msg) 86 | 87 | ### Logger:info ($msg) 88 | 89 | ### Logger::emergence ($msg) 90 | 91 | ### Logger::custom ($type = 'CUSTOM', $msg) 92 | 93 | * * * 94 | 95 | ## Flash 96 | 97 | Flash is a very useful helper in Kumbia that makes the messages of error, warning, informational and success output as standard. 98 | 99 | ### Flash::error ($text) 100 | 101 | — Send an error message to the user. Default is a message of letters red and pink background but these can be altered in the cascading style sheet class in public /css/style.css called error. 102 | 103 | Flash::error ("an error occurred"); 104 | 105 | * * * 106 | 107 | ### Flash::valid ($text) 108 | 109 | It allows to send a success message to the user. Default is a lyrics color message green and pastel green color background but these can be altered in the cascading style sheet class in public/css/style.css called valid. 110 | 111 | Flash: valid("Realized the process correctly"); 112 | 113 | * * * 114 | 115 | ### Flash:info ($text) 116 | 117 | It allows you to send information to the user. Default is a message of letters color blue and blue pastel-coloured background; but these can be altered in the cascading style sheet class in public/css/style.css called info. 118 | 119 | Flash::info("There are no results in the search"); 120 | 121 | * * * 122 | 123 | ### Flash:warning ($text) 124 | 125 | It allows to send a warning message to the user. Default is a message of letters color blue and pastel blue color background but these can be altered in the cascading style sheet class in public/css/style.css called warning. 126 | 127 | Flash:warning("Warning:_you_are_not_login_in_the_system"); 128 | 129 | * * * 130 | 131 | ### Flash::show($name, $text) 132 | 133 | ... 134 | 135 | * * * 136 | 137 | ## Session 138 | 139 | The Session class is to facilitate handling of the session. 140 | 141 | ### Session:set($index,_$value,_$namespace='default') 142 | 143 | Create or specify the value for an index of the current session. 144 | 145 | 146 | 147 | * * * 148 | 149 | ### Session: get ($index, $namespace ='default ') 150 | 151 | Get the value for an index of the current session. 152 | 153 | 156 | 157 | * * * 158 | 159 | ### Session:delete($index,_$namespace='default') 160 | 161 | Deletes the value for an index of the current session. 162 | 163 | 164 | 165 | * * * 166 | 167 | ### Session:has($index,_$namespace='default') 168 | 169 | Verify that this set the rate at the current session. 170 | 171 | 174 | 175 | * * * 176 | 177 | Note: $namespace is a single space in which may contain the session variables, avoiding collisions with variable names. 178 | 179 | ## Load 180 | 181 | Class load allows the loading of libraries in KumbiaPHP. 182 | 183 | ### Load::coreLib ($lib) 184 | 185 | It allows to load a KumbiaPHP core library. 186 | 187 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | * * * 334 | 335 | Default Auth2 takes the "login" field for the user name and the password 'password' field. 336 | 337 | To be able to start a user session and perform the authentication you must invoke the identify method, however depending on the adapter type, it is necessary to specify certain configuration settings. 338 | 339 | ### Adapter Model 340 | 341 | This adapter allows you to use authentication based on a model which inherits from the ActiveRecord class, verifying authentication at the database data. 342 | 343 | #### setModel() 344 | 345 | Sets the ActiveRecord model that is used as a data source. By default the model that is used as a data source is 'users'. 346 | 347 | $model (string): model name in lowercase 348 | 349 | setModel ($model) 350 | 351 | Example: 352 | 353 | $auth->setModel ('user'); 354 | 355 | * * * 356 | 357 | #### identify() 358 | 359 | Performs the authentication. If there is already an active user session or user data are correct, then the identification is satisfactory. 360 | 361 | return true or false 362 | 363 | identify() 364 | 365 | Example: 366 | 367 | $valid = $auth->identify(); 368 | 369 | * * * 370 | 371 | #### logout() 372 | 373 | End of the user session. 374 | 375 | logout() 376 | 377 | Example: 378 | 379 | $auth->logout(); 380 | 381 | * * * 382 | 383 | #### setFields() 384 | 385 | Sets the fields of the model that are loaded into session using the Session:set method. By default load the field 'id'. 386 | 387 | $fields (array): array fields 388 | 389 | setFields ($fields) 390 | 391 | Example: 392 | 393 | $auth->setFields (array ('id', 'user')); 394 | 395 | * * * 396 | 397 | #### setSessionNamespace() 398 | 399 | Sets a namespace for fields that are loaded into session. 400 | 401 | $namespace (string): session namespace 402 | 403 | setSessionNamespace($namespace) 404 | 405 | Example: 406 | 407 | $auth->setSessionNamespace ('auth'); 408 | 409 | * * * 410 | 411 | #### isValid() 412 | 413 | Check if there is an authenticated user session. 414 | 415 | return true or false 416 | 417 | isValid() 418 | 419 | Example: 420 | 421 | $valid = $auth->isValid(); 422 | 423 | * * * 424 | 425 | #### getError() 426 | 427 | Gets the error message. 428 | 429 | return string 430 | 431 | getError() 432 | 433 | Example: 434 | 435 | if(!$auth->identify()) flash:error ($auth->getError()); 436 | 437 | * * * 438 | 439 | #### setAlgos() 440 | 441 | Sets the user password encryption method. 442 | 443 | $algos (string): method of encryption, the name matches the php hash function. 444 | 445 | setAlgos ($algos) 446 | 447 | Example: 448 | 449 | $auth->setAlgos ('md5'); 450 | 451 | * * * 452 | 453 | #### setKey() 454 | 455 | Sets the key to identifying whether a session authenticated, this key takes a Boolean value of "true" when the authenticated session is valid, assigned by using the Session:set method. 456 | 457 | $key (string): session key 458 | 459 | setKey ($key) 460 | 461 | Example: 462 | 463 | $auth->setKey('user_logged'); 464 | 465 | * * * 466 | 467 | #### setCheckSession() 468 | 469 | It indicates that not start session from a different browser on the same IP. 470 | 471 | $check (boolean): indicator 472 | 473 | setCheckSession ($check) 474 | 475 | Example: 476 | 477 | $auth->setCheckSession(true); 478 | 479 | * * * 480 | 481 | #### setPass() 482 | 483 | Assigns the name of field for the key field. This field must correspond with the data base and the form field. Default is "password". 484 | 485 | $field (string): name of field that receives by POST. 486 | 487 | setPass($field) 488 | 489 | Example: 490 | 491 | $auth->setPass('key'); 492 | 493 | * * * 494 | 495 | #### setLogin() 496 | 497 | Assigns the name of the field for the user name field. This field must correspond with the data base and the form field. Default is "login". 498 | 499 | $field (string): name of field that receives by POST. 500 | 501 | setLogin ($field) 502 | 503 | Example: 504 | 505 | $auth->setLogin ('user'); 506 | 507 | * * * 508 | 509 | #### Get the fields loaded on session 510 | 511 | The fields are obtained through the Session:get method. 512 | 513 | $id = Session::get('id'); 514 | 515 | * * * 516 | 517 | If you have specified a namespace of session, you must then specify it by invoking the method. 518 | 519 | $id = Session::get('id', 'my_namespace'); 520 | 521 | * * * 522 | 523 | #### Example 524 | 525 | The view: 526 | 527 | app/views/access/login.phtml 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | * * * 545 | 546 | Controller: 547 | 548 | app/controllers/auth_controller.php 549 | 550 | login()) { Router::toAction('usuario/panel'); } } public function logout() { // Termina la sesion Load::model('usuario')->logout(); Router::toAction('login'); } } ?> 563 | 564 | * * * 565 | 566 | To validate this authenticated the user, just add the following code in any controller action or method before_filter: 567 | 568 | if(!Load::model('user')->logged()) { 569 | 570 | Router:toAction('auth/login'); 571 | 572 | 573 | return false; 574 | 575 | 576 | } 577 | 578 | * * * 579 | 580 | Model: 581 | 582 | app/models/usuario.php 583 | 584 | setModel ('user'); if($auth->identify()) return true; Flash:error($auth->getError()); return false; } / * * End * * / public function logout() {Auth2:factory('model') - > logout();} } / * * Check if this authenticated user * @return boolean * / public function logged() {return Auth2:factory('model') - > isValid();} } 595 | 596 | 597 | } -------------------------------------------------------------------------------- /en/index.md: -------------------------------------------------------------------------------- 1 | # Topics List 2 | 3 | ## Intro 4 | 5 | - [Preface](preface.md#prefacio) 6 | - [Special Thanks](preface.md#agradecimietos) 7 | - [About the Manual](preface.md#acerca-del-manual) 8 | - [About Kumbia](preface.md#acerca-de-kumbia) 9 | - [About the community](preface.md#sobre-la-comunidad) 10 | - [Why use KumbiaPHP Framework?](preface.md#porque-usar-kumbiaphp-framework) 11 | - [What does KumbiaPHP?](preface.md#qué-aporta-kumbiaphp) 12 | - [Front Controller](front-controller.md) 13 | - [Model, view, controller (MVC)](mvc.md#modelo,-vista,-controlador-mvc) 14 | - [What is MVC?](mvc.md#que-es-mvc) 15 | - [How KumbiaPHP apply the MVC?](mvc.md#como-kumbiaphp-aplica-el-mvc) 16 | - [Additional information](mvc.md#más-información) 17 | - [Case study (example of change)](mvc.md#caso-practico-cambiar-ejemplo) 18 | 19 | ## How to get started 20 | 21 | - [Install KumbiaPHP](to-install.md#instalar-kumbiaphp) 22 | - [Requirements](to-install.md#requisitos) 23 | - [Configure Web server](to-install.md#configurar-servidor-web) 24 | - [Enabling mod_rewrite of Apache on GNU/Linux (Debian, Ubuntu and derivatives)](to-install.md#habitando-mod_rewrite-de-apache-en-gnu/linux-debian,-ubuntu-y-derivados) 25 | - [Why is important Mod-Rewrite?](to-install.md#por-que-es-importante-el-mod-rewrite) 26 | - [My first app with KumbiaPHP](first-app.md#mi-primera-aplicación-con-kumbiaphp) 27 | - [Hello, KumbiaPHP!](first-app.md#hola,-kumbiaphp!) 28 | - [Controller](first-app.md#el-controlador) 29 | - [View](first-app.md#la-vista) 30 | - [KumbiaPHP and URLs](first-app.md#kumbiaphp-y-sus-urls) 31 | - [Add more content](first-app.md#agregando-mas-contenido) 32 | - [Repeating history](first-app.md#repitiendo-la-historia) 33 | - [Configuration files](configuration.md) 34 | - [config/config.php](configuration.md#configuration-configconfigphp-file) 35 | - [config/exception.php](configuration.md#configuration-configexceptionphp-file-v-12) 36 | - [CRUD](crud.md) - [Intro](crud.md#introducción) - [database.ini configuration](crud.md#configurando-database.ini) - [Model](crud.md#modelo) - [Controller](crud.md#controller) - [Views](crud.md#vistas) - [CRUD test](crud.md#probando-el-crud) 37 | 38 | ## MCV components 39 | 40 | - [Controller](controller.md#el-controlador) 41 | - [Front Controller](controller.md#controlador-frontal) 42 | - [Breaking down Front Controller](controller.md#destripando-el-front-controller) 43 | - [Deafult Front Controller](controller.md#front-controller-por-defecto) 44 | - [KumbiaPHP constants](controller.md#constantes-de-kumbiaphp) 45 | - [APP_PATH](controller.md#app_path) 46 | - [CORE_PATH](controller.md#core_path) 47 | - [PUBLIC_PATH](controller.md#public_path) 48 | - [The actions](controller.md#las-acciones) 49 | - [Actions and views](controller.md#las-acciones-y-las-vistas) 50 | - [Getting values from an action](controller.md#obtener-valores-desde-una-accion) 51 | - [Controller conventions and creation](controller.md#convenciones-y-creacion-de-un-controlador) 52 | - [Conventions](controller.md#convenciones) 53 | - [Controller creation](controller.md#creacion-de-un-controlador) 54 | - [Class AppController](controller.md#clase-appcontroller) 55 | - [Actions and Controllers by default](controller.md#acciones-y-controladores-por-defecto) 56 | - [Filters](controller.md#filtros) 57 | - [Controller Filters](controller.md#filtros-de-controladores) 58 | - [initialize()](controller.md#initialize) 59 | - [finalize()](controller.md#finalize) 60 | - [Action filters](controller.md#filtros-de-acciones) 61 | - [before_filter()](controller.md#before_filter) 62 | - [after_filter()](controller.md#after_filter) 63 | - [View](view.md#la-vista) 64 | - [Sending data to the View](view.md#pasando-datos-a-la-vista) 65 | - [Output buffer](view.md#buffer-de-salida) 66 | - [Template](view.md#template) 67 | - [How to create a Template?](view.md#como-crear-un-template) 68 | - [How to use a Template?](view.md#como-utilizar-un-template) 69 | - [Sending data to the Template](view.md#pasando-datos-al-template) 70 | - [Partial](view.md#partial) 71 | - [How to create a Partial?](view.md#como-crear-un-partial) 72 | - [How to use a Partial?](view.md#como-utilizar-un-partial) 73 | - [Sending data to a Partial](view.md#pasando-datos-a-los-partials) 74 | - [Grouping in directories](view.md#agrupando-en-directorios) 75 | - [View grouping example](view.md#ejemplo-de-agrupacion-de-vista) 76 | - [Partial grouping example](view.md#ejemplo-de-agrupacion-de-partial) 77 | - [Template grouping example](view.md#ejemplo-de-agrupacion-de-template) 78 | - [Response types](view.md#tipos-de-respuestas) 79 | - [Cache usage in views](view.md#uso-de-cache-en-las-vistas) 80 | - [Views Cache](view.md#cache-de-vistas) 81 | - [Groups of views in cache](view.md#grupos-de-vistas-en-cache) 82 | - [Templates Cache](view.md#cache-de-templates) 83 | - [Partials Cache](view.md#cache-de-partials) 84 | - [Helpers](view.md#helpers) 85 | - [Html class](view.md#clase-html) 86 | - [Html::img()](view.md#html::img) 87 | - [Html::link()](view.md#html::link) 88 | - [Html::lists()](view.md#html::lists) 89 | - [Html::gravatar()](view.md#html::gravatar) 90 | - [Html::includeCss()](view.md#html::includecss) 91 | - [Html::meta()](view.md#html::meta) 92 | - [Html::includeMetatags()](view.md#html::includemetatags) 93 | - [Html::headLink()](view.md#html::headlink) 94 | - [HTML::headLinkAction()](view.md#html::headlinkaction) 95 | - [Html::headLinkResource()](view.md#html::headlinkresource) 96 | - [Html::includeHeadLinks()](view.md#html::includeheadlinks) 97 | - [Tag Class](view.md#clase-tag) 98 | - [Tag::css()](view.md#tag::css) 99 | - [Tag::js()](view.md#tag::js) 100 | - [Including a JavaScript file to a view, partial or template](view.md#incluye-un-archivo-javascript-a-la-vista,-partial-o-template) 101 | - [Clase Form](view.md#clase-form) 102 | - [Form::open()](view.md#form::open) 103 | - [Form::openMultipart()](view.md#form::openmultipart) 104 | - [Form::close()](view.md#form::close) 105 | - [Form::input()](view.md#form::input) 106 | - [Form::text()](view.md#form::text) 107 | - [Form::pass()](view.md#form::pass) 108 | - [Form::textarea()](view.md#form::textarea) 109 | - [Form::label()](view.md#form::label) 110 | - [Form::hidden()](view.md#form::hidden) 111 | - [Form::dbSelect()](view.md#form::dbselect) 112 | - [Form::select()](view.md#form::select) 113 | - [Form::file()](view.md#form::file) 114 | - [Form::button()](view.md#form::button) 115 | - [Form::submitImage()](view.md#form::submitimage) 116 | - [Form::submit()](view.md#form::submit) 117 | - [Form::reset()](view.md#form::reset) 118 | - [Form::check()](view.md#form::check) 119 | - [Form::radio()](view.md#form::radio) 120 | - [Js](view.md#js) 121 | - [Js::link ()](view.md#js::link-) 122 | - [Js::linkAction ()](view.md#js::linkaction-) 123 | - [Js::submit ()](view.md#js::submit-) 124 | - [Js::submitImage ()](view.md#js::submitimage-) 125 | - [Ajax](view.md#ajax) 126 | - [Ajax::link()](view.md#ajax::link) 127 | - [Ajax::linkAction()](view.md#ajax::linkaction) 128 | - [Models](model.md#modelos) 129 | - [How to use models](model.md#como-usar-los-modelos) 130 | 131 | ## ActiveRecord 132 | 133 | - [ActiveRecord](active-record.md#activerecord) 134 | - [Ventajas del ActiveRecord](active-record.md#ventajas-del-activerecord) 135 | - [Crear un Modelo en Kumbia PHP Framework](active-record.md#crear-un-modelo-activerecord-en-kumbiaphp-framework) 136 | - [Columnas y Atributos](active-record.md#columnas-y-atributos) 137 | - [Llaves Primarias y el uso de IDs](active-record.md#llaves-primarias-y-el-uso-de-ids) 138 | - [Convenciones en ActiveRecord](active-record.md#convenciones-en-activerecord) 139 | - [ActiveRecord API](active-record.md#activerecord-api) 140 | - [Consultas](active-record.md#consultas) 141 | - [distinct ()](active-record.md#distinct-) 142 | - [find_all_by_sql (string $sql)](active-record.md#find_all_by_sql-string-sql) 143 | - [find_by_sql (string $sql)](active-record.md#find_by_sql-string-sql) 144 | - [find_first (string $sql)](active-record.md#find_first-string-sql) 145 | - [find ()](active-record.md#find) 146 | - [select_one(string $select_query)](active-record.md#select_one-string-select_query) 147 | - [select_one(string $select_query) (static)](active-record.md#select_one-string-select_query-static) 148 | - [exists()](active-record.md#exists) 149 | - [find_all_by()](active-record.md#find_all_by) 150 | - [find_by_*campo*()](active-record.md#find_by_campo) 151 | - [find_all_by_*campo*()](active-record.md#find_all_by_campo) 152 | - [Conteos y sumatorias](active-record.md#conteos-y-sumatorias) 153 | - [count()](active-record.md#count) 154 | - [sum()](active-record.md#sum) 155 | - [count_by_sql()](active-record.md#count_by_sql) 156 | - [Promedios, máximo y mínimo](active-record.md#promedios-máximo-y-mínimo) 157 | - [average()](active-record.md#average) 158 | - [maximum()](active-record.md#maximum) 159 | - [minimum()](active-record.md#minimum) 160 | - [Creación, actualización y borrado de registros](active-record.md#creación-actualización-y-borrado-de-registros) 161 | - [create()](active-record.md#create) 162 | - [save()](active-record.md#save) 163 | - [update()](active-record.md#update) 164 | - [update_all()](active-record.md#update_all) 165 | - [delete()](active-record.md#delete) 166 | - [delete_all()](active-record.md#delete_all) 167 | - [Validaciones](active-record.md#validaciones) 168 | - [validates_presence_of()](active-record.md#validates_presence_of) 169 | - [validates_length_of()](active-record.md#validates_length_of) 170 | - [validates_numericality_of()](active-record.md#validates_numericality_of) 171 | - [validates_email_in()](active-record.md#validates_email_in) 172 | - [validates_uniqueness_of()](active-record.md#validates_uniqueness_of) 173 | - [validates_date_in()](active-record.md#validates_date_in) 174 | - [validates_format_of()](active-record.md#validates_format_of) 175 | - [Transacciones](active-record.md#transacciones) 176 | - [commit()](active-record.md#commit) 177 | - [begin()](active-record.md#begin) 178 | - [rollback()](active-record.md#rollback) 179 | - [Otros métodos](active-record.md#otros-métodos) 180 | - [sql](active-record.md#sql-string-sql) 181 | - [Callbacks](active-record.md#callbacks) 182 | - [before_validation](active-record.md#before_validation) 183 | - [before_validation_on_create](active-record.md#before_validation_on_create) 184 | - [before_validation_on_update](active-record.md#before_validation_on_update) 185 | - [after_validation_on_create](active-record.md#after_validation_on_create) 186 | - [after_validation_on_update](active-record.md#after_validation_on_update) 187 | - [after_validation](active-record.md#after_validation) 188 | - [before_save](active-record.md#before_save) 189 | - [before_update](active-record.md#before_update) 190 | - [before_create](active-record.md#before_create) 191 | - [after_update](active-record.md#after_update) 192 | - [after_create](active-record.md#after_create) 193 | - [after_save](active-record.md#after_save) 194 | - [before_delete](active-record.md#before_delete) 195 | - [after_delete](active-record.md#after_delete) 196 | - [Asociaciones](active-record.md#asociaciones) 197 | - [Pertenece (belongs_to)](active-record.md#pertenece-belongs_to) 198 | - [Tiene un (has_one)](active-record.md#tiene-un-has_one) 199 | - [Tiene muchos (has_many)](active-record.md#tiene-muchos-has_many) 200 | - [Tiene y pertenece a muchos (has_and_belongs_to_many)](active-record.md#tiene-y-pertenece-a-muchos-has_and_belongs_to_many) 201 | - [Paginadores](active-record.md#paginadores) 202 | - [paginate()](active-record.md#paginate) 203 | - [paginate_by_sql()](active-record.md#paginate_by_sql) 204 | - [Paginando en ActiveRecord](active-record.md#paginando-en-activerecord) 205 | - [Ejemplo completo de uso del paginador](active-record.md#ejemplo-completo-de-uso-del-paginador) 206 | 207 | ## Otros Componentes 208 | 209 | - [Clases padre](parent-class.md#clases-padre) 210 | - [AppController](parent-class.md#appcontroller) 211 | - [View](parent-class.md#view) 212 | - [Libs de KumbiaPHP](parent-class.md#libs-de-kumbiaphp) 213 | - [Cache](parent-class.md#cache) 214 | - [driver($driver=null)](parent-class.md#driver$driver=null) 215 | - [get($id, $group='default')](parent-class.md#get$id,-$group='default') 216 | - [save($value, $lifetime=null, $id=false, $group='default')](parent-class.md#save$value,-$lifetime=null,-$id=false,-$group='default') 217 | - [start ($lifetime, $id, $group='default')](parent-class.md#start-$lifetime,-$id,-$group='default') 218 | - [end ($save=true)](parent-class.md#end-$save=true) 219 | - [Logger](parent-class.md#logger) 220 | - [Logger::warning ($msg);](parent-class.md#logger::warning-$msg;) 221 | - [Logger::error ($msg)](parent-class.md#logger::error-$msg) 222 | - [Logger::debug ($msg)](parent-class.md#logger::debug-$msg) 223 | - [Logger::alert ($msg)](parent-class.md#logger::alert-$msg) 224 | - [Logger::critical ($msg)](parent-class.md#logger::critical-$msg) 225 | - [Logger::notice ($msg)](parent-class.md#logger::notice-$msg) 226 | - [Logger::info ($msg)](parent-class.md#logger::info-$msg) 227 | - [Logger::emergence ($msg)](parent-class.md#logger::emergence-$msg) 228 | - [Logger::custom ($type='CUSTOM', $msg)](parent-class.md#logger::custom-$type='custom',-$msg) 229 | - [Flash](parent-class.md#flash) 230 | - [Flash::error($text)](parent-class.md#flash::error$text) 231 | - [Flash::valid($text)](parent-class.md#flash::valid$text) 232 | - [Flash::info($text)](parent-class.md#flash::info$text) 233 | - [Flash::warning($text)](parent-class.md#flash::warning$text) 234 | - [Flash::show($name, $text)](parent-class.md#flash::show$name,-$text) 235 | - [Session](parent-class.md#session) 236 | - [Session::set($index, $value, $namespace='default')](parent-class.md#session::set$index,-$value,-$namespace='default') 237 | - [Session::get($index, $namespace='default')](parent-class.md#session::get$index,-$namespace='default') 238 | - [Session::delete($index, $namespace='default')](parent-class.md#session::delete$index,-$namespace='default') 239 | - [Session::has($index, $namespace='default')](parent-class.md#session::has$index,-$namespace='default') 240 | - [Load](parent-class.md#load) 241 | - [Load::coreLib($lib)](parent-class.md#load::corelib$lib) 242 | - [Load::lib($lib)](parent-class.md#load::lib$lib) 243 | - [Load::model($model)](parent-class.md#load::model$model) 244 | - [Auth2](parent-class.md#auth2) 245 | - [Solicitando un adaptador](parent-class.md#solicitando-un-adaptador) 246 | - [Adaptador predeterminado](parent-class.md#adaptador-predeterminado) 247 | - [Como trabaja la autenticación](parent-class.md#como-trabaja-la-autenticacion) 248 | - [Adaptador Model](parent-class.md#adaptador-model) 249 | - [setModel()](parent-class.md#setmodel) 250 | - [identify()](parent-class.md#identify) 251 | - [logout()](parent-class.md#logout) 252 | - [setFields()](parent-class.md#setfields) 253 | - [setSessionNamespace()](parent-class.md#setsessionnamespace) 254 | - [isValid()](parent-class.md#isvalid) 255 | - [getError()](parent-class.md#geterror) 256 | - [setAlgos()](parent-class.md#setalgos) 257 | - [setKey()](parent-class.md#setkey) 258 | - [setCheckSession()](parent-class.md#setchecksession) 259 | - [setPass()](parent-class.md#setpass) 260 | - [setLogin()](parent-class.md#setlogin) 261 | - [Obtener los campos cargados en sesión](parent-class.md#obtener-los-campos-cargados-en-sesion) 262 | - [Ejemplo](parent-class.md#ejemplo) 263 | - [La Consola](console.md#la-consola) 264 | - [Introducción](console.md#introduccion) 265 | - [Como utilizar la Consola](console.md#como-utilizar-la-consola) 266 | - [Consolas de KumbiaPHP](console.md#consolas-de-kumbiaphp) 267 | - [Cache](console.md#cache) 268 | - [clean \[group\] \[--driver\]](console.md#clean-[group]-[--driver]) 269 | - [Permite limpiar la cache.](console.md#permite-limpiar-la-cache.) 270 | - [Argumentos secuenciales:](console.md#argumentos-secuenciales:) 271 | - [Argumentos con nombre:](console.md#argumentos-con-nombre:) 272 | - [Ejemplo:](console.md#ejemplo:) 273 | - [php ../../core/console/kumbia.php cache clean](console.md#php-../../core/console/kumbia.php-cache-clean) 274 | - [remove \[id\] \[group\]](console.md#remove-[id]-[group]) 275 | - [Model](console.md#model) 276 | - [create [model]](console.md#create-[model]) 277 | - [delete [model]](console.md#delete-[model]) 278 | - [Controller](console.md#controller) 279 | - [create [controller]](console.md#create-[controller]) 280 | - [delete [controller]](console.md#delete-[controller]) 281 | - [](console.md#) 282 | - [Desarrollando tus Consolas](console.md#desarrollando-tus-consolas) 283 | - [Console::input](console.md#console::input) 284 | 285 | ## Apendice 286 | 287 | - [Apéndices](appendix.md#apendices) 288 | - [Integración de jQuery y KumbiaPHP](appendix.md#integracion-de-jquery-y-kumbiaphp) 289 | - [KDebug](appendix.md#kdebug) 290 | - [Aplicación en producción](appendix.md#aplicacion-en-producción) 291 | - [Partials de paginación](appendix.md#partials-de-paginacion) 292 | - [Classic](appendix.md#classic) 293 | - [Digg](appendix.md#digg) 294 | - [Extended](appendix.md#extended) 295 | - [Punbb](appendix.md#punbb) 296 | - [Simple](appendix.md#simple) 297 | - [Ejemplo de uso](appendix.md#ejemplo-de-uso) 298 | - [Auth](appendix.md#auth) 299 | - [Beta1 a Beta2](appendix.md#beta1-a-beta2) 300 | - [Deprecated](appendix.md#deprecated) 301 | - [Métodos y clases que se usaban en versiones anteriores y que aun](appendix.md#metodos-y-clases-que-se-usaban-en-versiones-anteriores-y-que-aun) 302 | - [Lista de cambios entre versiones: si no se especifica beta1 es que es](appendix.md#lista-de-cambios-entre-versiones:-si-no-se-especifica-beta1-es-que-es) 303 | - [Cambio en las rutas entre versiones:](appendix.md#cambio-en-las-rutas-entre-versiones:) 304 | - [0.5 => 1.0 beta1](appendix.md#0.5-=>-1.0-beta1) 305 | - [1.0 beta1 => 1.0 beta2](appendix.md#1.0-beta1-=>-1.0-beta2) 306 | - [Glosario](appendix.md#glosario) 307 | --------------------------------------------------------------------------------