Ticker

6/recent/ticker-posts

Desarrollando nuestro proyecto base FrontEnd en CodeIgniter 4


Continuando con la serie de tutoriales prácticos acerca del desarrollo de proyectos web haciendo uso del Framework de CodeIgniter en su versión 4, en este tutorial desarrollaremos nuestro proyecto base FrontEnd para posteriores desarrollo de nuevos sitios web.

Requisitos:

  1. Apache 2.4.58 (Win64)
  2. OpenSSL 3.1.3 
  3. PHP 8.1.25
  4. phpMyAdmin 5.2.1
  5. CodeIgniter 4
  6. XAMPP Control Panel v3.3.0
  7. Visual Studio Code
  8. HTML y CSS


Lo que veremos en este tutorial:

  1. Crear las funciones en el Controller.
  2. Configura el enrutador inicial del proyecto.
  3. Crear directorios para los archivos Front-End.
  4. Crear el archivo y desarrollar el layout principal.
  5. Crear los archivos y desarrollar las Views Front-End.
  6. Validando el proyecto Front-End desde localhost.
  7. Conclusiones y referencias.


1. Crear las funciones en el Controller.

En el controlador Home realizamos algunas modificaciones a la función Index y agregamos nuevas funciones como about, services, projects y contact, las funciones (retornan las return view('pages\public\VIEWs', $this->data);) se encargarán de enviar los datos (se envian los datos page_title y page_description) a las Views del Front-End.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
        $this->data['page_title'] = "Home";
        $this->data['page_description'] = "Page home";
        return view('pages\public\home', $this->data);
    }

    public function about()
    {
        $this->data['page_title'] = "About";
        $this->data['page_description'] = "Page about";
        return view('pages\public\about', $this->data);
    }

    public function services()
    {
        $this->data['page_title'] = "Services";
        $this->data['page_description'] = "Page Services";
        return view('pages\public\services', $this->data);
    }

    public function projects()
    {
        $this->data['page_title'] = "Projects";
        $this->data['page_description'] = "Page projects";
        return view('pages\public\projects', $this->data);
    }

    public function contact()
    {
        $this->data['page_title'] = "Contact";
        $this->data['page_description'] = "Page contact";
        return view('pages\public\contact', $this->data);
    }
}


2. Configura el enrutador incial del proyecto.

Desde el archivo Routing.php ubicado en la ruta ..\ci4_base_project_front_end\app\Config se debe agregar la siguiente ruta: $routes->get('/', 'Home::index'); para referenciar a las vistas.

3. Crear directorios para los archivos Front-End.

En el directorio principal app del proyecto ci4_base_project_front_end creamos los directorios layouts pages, seguidamente en el directorio pages ceamos el directorio public.

..\ci4_base_project_front_end\app\Views\layouts
..\ci4_base_project_front_end\app\Views\pages\
..ci4_base_project_front_end\app\Views\pages\public

4. Crear el archivo y desarrollar el layout principal.

4.1. Crear el achivo el layout para el Front-End.


En el directorio layouts, debemos crear el archivo main.php que cumplirá la función de layout principal para el Front-End del sitio web, seguidamente desarrollamos el layout teniendo en cuenta los siguiente bloques: head, style, menu, renderSection, footer y scripts.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= isset($page_title) ? $page_title.' | ' : "" ?><?= env('short_name') ?>!</title>
    <meta name="description" content="The small template for Website Front End using CodeIgniter 4">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" type="image/png" href="<?= base_url('public/favicon.png')  ?>">
    <!-- HERE CODE STYLES -->
    
</head>
<body>
<!-- HEADER: MENU + HEROE SECTION -->
<header>

    <div class="menu">
        <ul>
            <li class="logo">
                <a href="https://hadsonpar.com" target="_blank">
                <img src="<?= base_url('public/hadsonpar.png')  ?>" alt="hadsonpar"/>
                </a>
            </li>
            <li class="menu-toggle">
                <button id="menuToggle">&#9776;</button>
            </li>
            <li class="menu-item hidden">
                <a class="nav-link <?= isset($page_title) && $page_title == 'Home' ? 'active' : '' ?>" aria-current="page" href="<?= base_url('') ?>">Home</a>
            </li>
            <li class="menu-item hidden">
                <a class="nav-link <?= isset($page_title) && $page_title == 'About' ? 'active' : '' ?>" href="<?= base_url('Home/about') ?>">About</a>
            </li>
            <li class="menu-item hidden">
                <a class="nav-link <?= isset($page_title) && $page_title == 'Services' ? 'active' : '' ?>" href="<?= base_url('Home/services') ?>">Services</a>
            </li>
            <li class="menu-item hidden">
                <a class="nav-link <?= isset($page_title) && $page_title == 'Projects' ? 'active' : '' ?>" href="<?= base_url('Home/projects') ?>">Projects</a>
            </li>
            <li class="menu-item hidden">
                <a class="nav-link <?= isset($page_title) && $page_title == 'Contact' ? 'active' : '' ?>" href="<?= base_url('Home/contact') ?>">Contact</a>
            </li>
        </ul>
    </div>

    <div class="heroe">
        <h1>Welcome to <?= env('system_name') ?><h1>
        <h3>by <a href="https://hadsonpar.com/" target="_blank"><?= env('developer_name') ?></a></h3>        
        <h2>The small framework with powerful features</h2>
    </div>

</header> 

<!-- CONTENT -->
<section>
    <?= $this->renderSection('content') ?>    
</section>

<!-- FOOTER: DEBUG INFO + COPYRIGHTS -->
<footer>
    <div class="author">

        <p><?= env('system_name') ?></p>        
        <p>Developed by <a href="https://hadsonpar.com/" target="_blank"> <?= env('developer_name') ?></a></p>

    </div>

    <div class="copyrights">
        <p>&copy; <?= date('Y') ?> CodeIgniter Foundation. CodeIgniter is open source project released under the MIT
            open source licence.</p>
    </div>
</footer>

<!--START SCRIPTS -->
<script {csp-script-nonce}>
    document.getElementById("menuToggle").addEventListener('click', toggleMenu);
    function toggleMenu() {
        var menuItems = document.getElementsByClassName('menu-item');
        for (var i = 0; i < menuItems.length; i++) {
            var menuItem = menuItems[i];
            menuItem.classList.toggle("hidden");
        }
    }
</script>
<!--END SCRIPTS -->

</body>
</html>


El bloque style se debe agregar en el bloque head del código HTML:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
<style {csp-style-nonce}>
        * {
            transition: background-color 300ms ease, color 300ms ease;
        }
        *:focus {
            background-color: rgba(221, 72, 20, .2);
            outline: none;
        }
        html, body {
            color: rgba(33, 37, 41, 1);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
            font-size: 16px;
            margin: 0;
            padding: 0;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            text-rendering: optimizeLegibility;
        }
        header {
            background-color: rgba(247, 248, 249, 1);
            padding: .4rem 0 0;
        }
        .menu {
            padding: .4rem 2rem;
        }
        header ul {
            border-bottom: 1px solid rgba(242, 242, 242, 1);
            list-style-type: none;
            margin: 0;
            overflow: hidden;
            padding: 0;
            text-align: right;
        }
        header li {
            display: inline-block;
        }
        header li a {
            border-radius: 5px;
            color: rgba(0, 0, 0, .5);
            display: block;
            height: 44px;
            text-decoration: none;
        }
        header li.menu-item a {
            border-radius: 5px;
            margin: 5px 0;
            height: 38px;
            line-height: 36px;
            padding: .4rem .65rem;
            text-align: center;
        }
        header li.menu-item a:hover,
        header li.menu-item a:focus {
            background-color: rgba(221, 72, 20, .2);
            color: rgba(221, 72, 20, 1);
        }
        header .logo {
            float: left;
            height: 44px;
            padding: .4rem .5rem;
        }
        header .menu-toggle {
            display: none;
            float: right;
            font-size: 2rem;
            font-weight: bold;
        }
        header .menu-toggle button {
            background-color: rgba(221, 72, 20, .6);
            border: none;
            border-radius: 3px;
            color: rgba(255, 255, 255, 1);
            cursor: pointer;
            font: inherit;
            font-size: 1.3rem;
            height: 36px;
            padding: 0;
            margin: 11px 0;
            overflow: visible;
            width: 40px;
        }
        header .menu-toggle button:hover,
        header .menu-toggle button:focus {
            background-color: rgba(221, 72, 20, .8);
            color: rgba(255, 255, 255, .8);
        }
        header .heroe {
            margin: 0 auto;
            max-width: 1100px;
            padding: 1rem 1.75rem 1.75rem 1.75rem;
        }
        header .heroe h1 {
            font-size: 2.5rem;
            font-weight: 500;
        }
        header .heroe h2 {
            font-size: 1.5rem;
            font-weight: 300;
        }
        section {
            margin: 0 auto;
            max-width: 1100px;
            padding: 2.5rem 1.75rem 3.5rem 1.75rem;
        }
        section h1 {
            margin-bottom: 2.5rem;
            font-size: 2.5rem;
            color: #ff5733;
        }
        section h2 {
            font-size: 120%;
            line-height: 2.5rem;
            padding-top: 1.5rem;
        }
        section pre {
            background-color: rgba(247, 248, 249, 1);
            border: 1px solid rgba(242, 242, 242, 1);
            display: block;
            font-size: .9rem;
            margin: 2rem 0;
            padding: 1rem 1.5rem;
            white-space: pre-wrap;
            word-break: break-all;
        }
        section code {
            display: block;
        }
        section a {
            color: rgba(221, 72, 20, 1);
        }
        section svg {
            margin-bottom: -5px;
            margin-right: 5px;
            width: 25px;
        }
        footer {
            background-color: rgba(221, 72, 20, .9);
            text-align: center;
        }
        footer .author {
            color: rgba(255, 255, 255, 1);
            padding: 2rem 1.75rem;
        }
        
        footer .author a {
            text-decoration: none;
            color: #fff;
            font-weight: bold;
        }

        footer .copyrights {
            background-color: rgba(62, 62, 62, 1);
            color: rgba(200, 200, 200, 1);
            padding: .25rem 1.75rem;
        }
        @media (max-width: 629px) {
            header ul {
                padding: 0;
            }
            header .menu-toggle {
                padding: 0 1rem;
            }
            header .menu-item {
                background-color: rgba(244, 245, 246, 1);
                border-top: 1px solid rgba(242, 242, 242, 1);
                margin: 0 15px;
                width: calc(100% - 30px);
            }
            header .menu-toggle {
                display: block;
            }
            header .hidden {
                display: none;
            }
            header li.menu-item a {
                background-color: rgba(221, 72, 20, .1);
            }
            header li.menu-item a:hover,
            header li.menu-item a:focus {
                background-color: rgba(221, 72, 20, .7);
                color: rgba(255, 255, 255, .8);
            }
        }
    </style>

4.2. Principales consideraciones:

¿Qué es y para que sirve renderSection en CodeIgniter 4?

CodeIgniter actualmente el método renderSection() al igual que incluye otros tecnologías desarrollo como es ASP.Net MVC, la principal funcionalidad del método renderSection() es actuar com un marcador de posición para el contenido de las páginas web, usalmente se incluye a páginas que cumplen la funcionalidad de layouts para un determinado sitio web. El método renderSection() tiene dos argumentos: $sectionName y $saveData, el argumento $sectionName es el nombre de la sección que utiliza para cualquier vista secundaria para nombrar la sección de contenido. En cuanto al argumento $saveData (es de tipo boleano) cumple la funcionalidad de guardar ($saveData debe estar en TRUE) los datos para las posteriores llamadas en las vistas (páginas) secundaria .

Estructura base del layout principal para el Front-End del sitio web.

El archivo main.php hace referencia a nuestro layout principal para nuestro front-end del sitio web. Nuestro layout principal esta elaborado en base a la estructura de un archivo HTML, es decir, se compone de las etiquetas HTML, head, body y footer; en el body se está agregando el menú principal y el bloque sección (section) que hace referencia al renderSection de CodeIgniter - sección o bloque que servirá para agregar el contenido necesario en las vistas (páginas HTML) del sitio web.

Nota: Todas los views (páginas HTML) están relacionados a este principal (main.php) layout.


5. Crear los archivos y desarrollar las Views Front-End.

En el directorio public creamos los ARCHIVOS PHP para generar las vistas del Front-End:

..ci4_base_project_front_end\app\Views\pages\public\home.php
..ci4_base_project_front_end\app\Views\pages\public\about.php
..ci4_base_project_front_end\app\Views\pages\public\services.php
..ci4_base_project_front_end\app\Views\pages\public\projects.php
..ci4_base_project_front_end\app\Views\pages\public\contact.php

Seguidamente agregamos (desarrollo) el siguiente bloque de código:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>

<h1><?= $page_description ?></h1>
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you will find it located at:</p>
<pre><code>app/Views/pages/pubic/<?= $page_title ?></code></pre>
<p>The corresponding controller for this page can be found at:</p>
<pre><code>app/Controller/<?= $page_title ?></code></pre>

<?= $this->endSection() ?>


En primer instancia se debe extender (<?= $this->extend('layouts/main') ?>) al archivo main.php que es el layout de nuestro sitio web, seguidamente se debe hacer referencia a la sección (método renderSection) de contenido (<?= $this->section('content') ?>) inicial, en dicho bloque se debe agregar toda la información necesaria que se mostrará en dicha vista (página), finalmen se debe finalizar el bloque de la sección (<?= $this->endSection() ?>).

Para las demás páginas (about.php, services.php, projects.php y contact.php) se debe extender el archivo main.php y agregar la sección inicial + CONTENIDO + sección final 


6. Validando el proyecto Front-End desde localhost.

Desde Google Chrome u otro navegador web se debe acceder a la URL del sitio web Front-End: http://localhost/ci4_base_project_front_end/ 




7. Conclusiones y Referencias.

Conclusiones.

En este tutorial desarrollamos las funciones necesarias en el Controller que retornan las vistas (páginas) del Front-End del sitio web. Además, desarrollamos nuestro layout principal teniendo en cuenta el método renderSection('content') de CodeIgniter 4: finalmente, explicamos acerca del método renderSection y se desarrollan las páginas del proyecto Front-End.


Referencias.


¡Hoy iniciamos una nueva historia de innovación y transformación digital!

Publicar un comentario

0 Comentarios