Static pages

Note: This tutorial assumes you’ve downloaded CodeIgniter andinstalled the framework in yourdevelopment environment.

The first thing you’re going to do is set up a controller to handlestatic pages. A controller is simply a class that helps delegate work.It is the glue of your web application.

For example, when a call is made to:

We might imagine that there is a controller named “news”. The methodbeing called on news would be “latest”. The news method’s job could be tograb 10 news items, and render them on the page. Very often in MVC,you’ll see URL patterns that match:

As URL schemes become more complex, this may change. But for now, thisis all we will need to know.

Let’s make our first controller

Create a file at app/Controllers/Pages.php with the followingcode.

  1. <?php namespace App\Controllers;
  2. use CodeIgniter\Controller;
  3.  
  4. class Pages extends Controller {
  5.  
  6. public function index()
  7. {
  8. return view('welcome_message');
  9. }
  10.  
  11. public function showme($page = 'home')
  12. {
  13. }
  14. }

You have created a class named Pages, with a showme method that acceptsone argument named $page. It also has an index() method, the sameas the default controller found in app/Controllers/Home.php; that methoddisplays the CodeIgniter welcome page.

The Pages class is extending theCodeIgniter\Controller class. This means that the new Pages class can access themethods and variables defined in the CodeIgniter\Controller class(system/Controller.php).

The controller is what will become the center of every request toyour web application. Like any php class, you refer toit within your controllers as $this.

Now that you’ve created your first method, it’s time to make some basic pagetemplates. We will be creating two “views” (page templates) that act asour page footer and header.

Create the header at app/Views/templates/header.php and addthe following code:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>CodeIgniter Tutorial</title>
  5. </head>
  6. <body>
  7.  
  8. <h1><?= $title; ?></h1>

The header contains the basic HTML code that you’ll want to displaybefore loading the main view, together with a heading. It will alsooutput the $title variable, which we’ll define later in the controller.Now, create a footer at app/Views/templates/footer.php thatincludes the following code:

  1. <em>&copy; 2019</em>
  2. </body>
  3. </html>

Adding logic to the controller

Earlier you set up a controller with a showme() method. The methodaccepts one parameter, which is the name of the page to be loaded. Thestatic page bodies will be located in the app/Views/pages/directory.

In that directory, create two files named home.php and about.php.Within those files, type some text − anything you’d like − and save them.If you like to be particularly un-original, try “Hello World!”.

In order to load those pages, you’ll have to check whether the requestedpage actually exists. This will be the body of the showme() methodin the Pages controller created above:

  1. public function showme($page = 'home')
  2. {
  3. if ( ! is_file(APPPATH.'/Views/pages/'.$page.'.php'))
  4. {
  5. // Whoops, we don't have a page for that!
  6. throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
  7. }
  8.  
  9. $data['title'] = ucfirst($page); // Capitalize the first letter
  10.  
  11. echo view('templates/header', $data);
  12. echo view('pages/'.$page, $data);
  13. echo view('templates/footer', $data);
  14. }

Now, when the requested page does exist, it is loaded, including the header andfooter, and displayed to the user. If the requested page doesn’t exist, a “404Page not found” error is shown.

The first line in this method checks whether the page actually exists.PHP’s native is_file() function is used to check whether the fileis where it’s expected to be. The PageNotFoundException is a CodeIgniterexception that causes the default error page to show.

In the header template, the $title variable was used to customize thepage title. The value of title is defined in this method, but instead ofassigning the value to a variable, it is assigned to the title elementin the $data array.

The last thing that has to be done is loading the views in the orderthey should be displayed. The view() method built-in toCodeIgniter will be used to do this. The second parameter in the view() method isused to pass values to the view. Each value in the $data array isassigned to a variable with the name of its key. So the value of$data['title'] in the controller is equivalent to $title in theview.

Note

Any files and directory names passed into the view() function MUSTmatch the case of the actual directory and file itself or the system willthrow errors on case-sensitive platforms.

Running the App

Ready to test? You cannot run the app using PHP’s built-in server,since it will not properly process the .htaccess rules that are provided inpublic, and which eliminate the need to specify “index.php/”as part of a URL. CodeIgniter has its own command that you can use though.

From the command line, at the root of your project:

  1. php spark serve

will start a web server, accessible on port 8080. If you set the location fieldin your browser to localhost:8080, you should see the CodeIgniter welcome page.

You can now try several URLs in the browser location field, to see what the _Pages_controller you made above produces…

  • localhost:8080/pages will show the results from the index methodinside our Pages controller, which is to display the CodeIgniter “welcome” page,because “index” is the default controller method
  • localhost:8080/pages/index will also show the CodeIgniter “welcome” page,because we explicitly asked for the “index” method
  • localhost:8080/pages/showme will show the “home” page that you made above,because it is the default “page” parameter to the showme() method.
  • localhost:8080/pages/showme/home will also show the “home” page that you made above,because we explicitly asked for it
  • localhost:8080/pages/showme/about will show the “about” page that you made above,because we explicitly asked for it
  • localhost:8080/pages/showme/shop will show a “404 - File Not Found” error page,because there is no app/Views/pages/shop.php

Routing

The controller is now functioning!

Using custom routing rules, you have the power to map any URI to anycontroller and method, and break free from the normal convention:http://example.com/[controller-class]/[controller-method]/[arguments]

Let’s do that. Open the routing file located atapp/Config/Routes.php and look for the “Route Definitions”section of the configuration file.

The only uncommented line there to start with should be::

  1. $routes->get('/', 'Home::index');

This directive says that any incoming request without any contentspecified should be handled by the index method inside the Home controller.

Add the following line, after the route directive for ‘/’.

  1. $routes->get('(:any)', 'Pages::showme/$1');

CodeIgniter reads its routing rules from top to bottom and routes therequest to the first matching rule. Each rule is a regular expression(left-side) mapped to a controller and method name separated by slashes(right-side). When a request comes in, CodeIgniter looks for the firstmatch, and calls the appropriate controller and method, possibly witharguments.

More information about routing can be found in the URI Routingdocumentation.

Here, the second rule in the $routes array matches any requestusing the wildcard string (:any). and passes the parameter to theview() method of the Pages class.

Now visit home. Did it get routed correctly to the showme()method in the pages controller? Awesome!

You should see something like the following:../_images/tutorial1.png