Static pages are managed using the MVC (Model-View-Controller) pattern. While they do not rely heavily on backend logic, they are served through controllers to maintain the MVC structure and allow for easier expansion in the future. Each page is associated with a controller method that loads the corresponding view file.
To create a static page, start by defining a method in a controller, such as about
or contact
. This method will use the view()
helper to load the content of a specific view file. For example, the about
method in the Pages
controller would load the about.php
file from the app/Views
directory.
The view files contain the HTML structure of the page and can include static text, images, and links. These files are stored in the app/Views
folder, maintaining separation between application logic and presentation.
Finally, configure routes in the app/Config/Routes.php
file to map specific URLs to the controller methods. For example, the URL /about
would point to the about
method of the Pages
controller.
1. Create a Controller
Create a new controller named Pages.php
in the app/Controllers
directory.
<?php
namespace App\Controllers;
class Pages extends BaseController
{
public function index()
{
return view('welcome_message'); // Default view
}
public function about()
{
return view('about'); // Static page
}
public function contact()
{
return view('contact'); // Static page
}
}
2. Create View Files
Create the view files for your static pages in the app/Views
directory.
app/Views/about.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About Us</title>
</head>
<body>
<h1>About Us</h1>
<p>Welcome to our about page. This is a static page example in CodeIgniter 4.</p>
</body>
</html>
app/Views/contact.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<p>Feel free to reach out to us through this page.</p>
</body>
</html>
3. Configure Routes
Update app/Config/Routes.php
to map the URLs to the appropriate methods in the Pages
controller.
$routes->get('/', 'Pages::index');
$routes->get('/about', 'Pages::about');
$routes->get('/contact', 'Pages::contact');
4. Web Browser Output
After setting up, you can access the static pages via a web browser:
- Homepage:
http://localhost:8080/
- About Page:
http://localhost:8080/about
- Contact Page:
http://localhost:8080/contact