Building A Simple Web App Using CodeIgniter 4 - Part 2 | MVC Basics

Tuan Sheroz Afridi Meedin
Mr. Meedin
Published in
10 min readJul 5, 2020

In Part 2 of this blog, we will be focusing mainly on the basics of CodeIgniter 4 evolving on top of the MVC Architecture.

Which involves, Routes, Views, Controllers and understanding them in detail with relevance to the Simple Blog that we are building.

Downloading a Code Editor

Visual Studio Code is my favorite Code Editor to work with. It is by far, one of the most popular Code Editors among Developers today. Any questions regarding the Code Editor can be dropped off to its massive community and contributors.

Downloading Visual Studio Code
Downloading Visual Studio Code

Selecting the Project Folder using Visual Studio Code

Select the Project Folder using Visual Studio Code.

File -> Open Folder -> Select Folder C:\xampp\htdocs\ci-4-simple-blog

Selecting the Project Folder using Visual Studio Code
Selecting the Project Folder using Visual Studio Code
Selecting the Project Folder path using Visual Studio Code
Selecting the Project Folder path using Visual Studio Code
How Visual Studio Code looks after selecting the project folder
How Visual Studio Code looks after selecting the project folder

Activate CodeIgniter 4 Environment (.env) Config File before starting development

Select the env file from the Project Root and rename it to .env. This in fact activates the Environment(.env) configuration file in the runtime. Adding more to it, when the file is renamed, the file icon switches from a Text to Setting icon.

env -> RMB -> Rename to .env

Renaming the env to .env to activate the file during runtime
Renaming the env to .env to activate the file during runtime
A change in the file icon. Text to setting.
A change in the file icon. Text to setting.

Switch the Environment from Production to Development in CodeIgniter 4

Switch the Environment from Production to Development in CodeIgniter 4
Switch the Environment from Production to Development in CodeIgniter 4
CI_ENVIRONMENT = production toCI_ENVIRONMENT = development

As you can see the configurations are commented so that they don’t execute and more of a template for developers to understand what could be included. By default the CodeIgniter 4 runs on top of a Production Environment. In order to change this we can remove the comment firstly and change the CI_ENVIRONMENT from production -> development. Changing to development enables various tools in CodeIgniter 4 when compared to CodeIgniter 3.

Final look after the switch from Production to Development in CodeIgniter 4
Final look after the switch from Production to Development in CodeIgniter 4

Defining the $baseURL

The $baseURL is the URL to your CodeIgniter root. Therefore it needs to be defined with the URL that we defined in PART 1.

Now we should be able to access the Web App via http://localhost:<PORT> and it should give us something like this.

Defining the $baseURL
Defining the $baseURL
//public $baseURL = 'http://localhost:8080/';
public $baseURL = 'http://localhost:8012/';

Now if we refresh the browser on http://localhost:<PORT>, we should be seeing something like this. Click on the CodeIgniter icon which appears on the right-bottom corner to view the CodeIgniter 4 debug console. Handy feature that the contributors have introduced compared to CodeIgniter 3.

When the Environment switches from Production to Development the developer console icon gets activated
When the Environment switches from Production to Development the developer console icon gets activated

If we look closely, the Environment has switched from production to development and the debug console has been activated.

Glimpse of the CodeIgniter 4 Developer console
Glimpse of the CodeIgniter 4 Developer console

Glimpse of one of the debug console tabs Vars which shows View Data, Session User Data, Request etc.

Glimpse of the Vars Tab in CodeIgniter 4 Developer console
Glimpse of the Vars Tab in CodeIgniter 4 Developer console

Configuring the Controllers

Lets create a new controller by duplicating the Controllers -> Home. Now that we have the copy of the Controller, lets rename the File and the Class name accordingly. I’ll be naming this new controller Controllers ->Pages.

Controllers are the heart of your application, as they determine how HTTP requests should be handled. Read More @ CodeIgniter.com

Configuring the Controllers
Configuring the Controllers

Edit the String returned in the index() function for us to witness the significant change.

public function index(){    return 'This is the Page Controller -> Index Function';}
Creating a new controller called Pages
Creating a new controller called Pages

Now if we access the controller using,

http://localhost:<PORT>/<CONTROLLER>, we should be seeing something like this. Please note the significant change that we made to the Controllers ->Pages -> index() function.

Accessing the pages controller
Accessing the pages controller

By default, when a Controller is accessed without a Suffix specifying a function, it would automatically pick the index() function. That is the reason as to why the String in the index() function is returned.

Creating a new Function in the Controller

Now that we have newly created controller Controllers ->Pages, lets create a new Function to make this Project interesting.

Creating a new Function in the Controller
Creating a new Function in the Controller
public function showme($page = 'home'){    return 'This Page is '.$page;}

Now if we access the controller using,

http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>, we should be seeing something like this.

In this case we have accessed the newly created showme() function. By default it takes home as the parameter String to be returned as we have defined it in the function $page = ‘home’. So it would be something more like this.

Accessing the pages controller showme function with the default parameter defined
Accessing the pages controller showme function with the default parameter defined

Lets try adding a suffix to the URL to pass a parameter to the newly created function and you should be seeing something like this. As the parameter suffix is passed, the browser showcases it dynamically.

Now if we access the controller using,

http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>/<PARAMS>, we should be seeing something like this.

Accessing the pages controller showme function with a parameter instead
Accessing the pages controller showme function with a parameter instead

Creating a the Views

So far we have worked on Controllers which is a vital part of any MVC Framework. Now lets get started by making changes to the User Interface. Under this topic, we will be creating the following views.

A visual on how Views will blend in later with relevance to the MVC architecture
A visual on how Views will blend in later with relevance to the MVC architecture

As per the image we can see that the MVC Framework is providing the facility of breaking down the User Interface to components/modules that can be combined to showcase dynamic content.

A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc.) if you need this type of hierarchy. Read More @ CodeIgniter.com

Views -> RMB -> New Folder -> Create a Folder called “pages”

Creating a new folder called pages in the Views folder
Creating a new folder called pages in the Views folder

Views -> pages-> RMB -> New File -> Create 2 files called “about” and “home”

Creating a new file in the newly created pages folder
Creating a new file in the newly created pages folder
Created two new views called about and home in the pages folder
Created two new views called about and home in the pages folder

Views -> RMB -> New Folder -> Create a Folder called “templates”

Creating a new folder called templates in the Views folder

Views -> templates-> RMB -> New File -> Create 2 files called “header”and “footer”

Creating a new file in the newly created templates folder
Creating a new file in the newly created templates folder
Created two new views called header and footer in the templates folder
Created two new views called header and footer in the templates folder

Building the Views Overall Structure

It is important that we keep in mind that the MVC facilitates us with the modular/component wise development and therefore chunks of code will be segmented accordingly. Will make sense as we build step by step.

A visual on how Views will blend in later with relevance to the MVC architecture
A visual on how Views will blend in later with relevance to the MVC architecture

Lets us start by generating the HTML structure using the Visual Studio Code IntelliSense. Type doc and use the shortcut Ctrl + Space for IntelliSense. Select the doc code base provided by the IntelliSense and click Enter else feel free to write down the HTML structure all by yourself by referring to trusted sources like w3schools.com.

Using IntelliSense to get the HTML structure to proceed with development
Using IntelliSense to get the HTML structure to proceed with development
HTML structure using IntelliSense
HTML structure using IntelliSense
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-       scale=1.0"><title>Document</title></head><body></body></html>

Now that we have the entire HTML structure lets break them down to modules/components.

Getting rid of the code relevant to the footer.php view
Getting rid of the code relevant to the footer.php view
</body></html>
Pasting relevant code to the footer.php view from the header.php view
Pasting relevant code to the footer.php view from the header.php view

Building the Views using Bootstrap 4

Building the Views using Bootstrap 4
Building the Views using Bootstrap 4
Copying the Bootstrap 4 CSS related CDNs
Copying the Bootstrap 4 CSS related CDNs
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
Pasting the Bootstrap 4 CSS related CDNs in the header.php view inside the <head></head> element
Pasting the Bootstrap 4 CSS related CDNs in the header.php view inside the <head></head> tag
Copying the Bootstrap 4 JS related CDNs
Copying the Bootstrap 4 JS related CDNs
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script><script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
Pasting the Bootstrap 4 JS related CDNs in the footer.php right before the </body> tag
Pasting the Bootstrap 4 JS related CDNs in the footer.php right before the </body> tag
Editing the home.php view with a <h1> tag to identify the page
Editing the home.php view with a <h1> tag to identify the page
Editing the about.php view with a <h1> tag to identify the page
Editing the about.php view with a <h1> tag to identify the page

Loading the Views created using the Controller

Now that we have the views creates, its high time that we load all these views using the Controller. As you can see the Views are loaded in the Controller in a Modular format. That way views can be reused and used for complex User Interface building.

Loading the created views from the controller to showcase them on the browser
Loading the created views from the controller to showcase them on the browser
echo view('templates/header');echo view('pages/'.$page);echo view('templates/footer');

Now if we access the controller using,

http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>, we should be seeing something like this.

Accessing the Web App using http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>
Accessing the Web App using http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>

Now if we access the controller using,

http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>/<PARAMS>, we should be seeing something like this.

Accessing the Web App using http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>/<PARAMS>
Accessing the Web App using http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>/<PARAMS>

Error Handling in the Controller

The following block of code ensures that if the passed parameters fail to find an existing view, it would throw a PageNotFoundException.

Error handling in the controller to mitigate access to views that do not exist
Error handling in the controller to mitigate access to views that do not exist
// check if the view existif(!is_file(APPPATH.'views/pages/'.$page.'.php')){    // throw error    throw new \CodeIgniter\Exceptions\PageNotFoundException($page);}

As we know, for now we have the Views home and about defined in the

Views-> pages folder. If in case the user tries to access a view which does not exist then the following error is thrown.

PageNotFoundException is thrown when the user tries to access a view that does not exist
PageNotFoundException is thrown when the user tries to access a view that does not exist

Continuing to enhance the User Interface using Bootstrap 4…

Continuing to enhance the User Interface using Bootstrap 4
Continuing to enhance the User Interface using Bootstrap 4
<section></section>
Searching for the Jumbotron component in Bootstrap 4
Searching for the Jumbotron component in Bootstrap 4
Copying the Jumbotron component from Bootstrap 4
Copying the Jumbotron component from Bootstrap 4
Pasting the Jumbotron component from Bootstrap 4 to the home.php view
Pasted the Jumbotron component from Bootstrap 4 to the home.php view
Jumbotron component is now showcased in the home page when accessed via a browser
Jumbotron component is now showcased in the home page when accessed via a browser

Try Editing the home.php View by yourself to get an output like this at the end.

Modified Jumbotron component is now showcased in the home page when accessed via a browser
Modified Jumbotron component is now showcased in the home page when accessed via a browser
Using the Jumbotron component in the about.php view as well
Using the Jumbotron component in the about.php view as well
<section>    <div class="jumbotron">       <h1 class="display-4">About Us!</h1>       <p class="lead">CI is a cook framework to build Web Apps.</p>    </div></section>
Jumbotron component is now showcased in the about page when accessed via a browser

Adding a Navigation bar using Bootstrap 4

Adding a Navigation bar using Bootstrap 4
Adding a Navigation bar using Bootstrap 4
Searching for the Navbar component in Bootstrap 4
Searching for the Navbar component in Bootstrap 4
Copying the Navbar component from Bootstrap 4
Copying the Navbar component from Bootstrap 4
Pasted the Navbar component from Bootstrap 4 to the header.php view and modified accordingly as well
Pasted the Navbar component from Bootstrap 4 to the header.php view and modified accordingly as well
Navbar component is now showcased in any page when accessed via a browser
Navbar component is now showcased in any page when accessed via a browser

Working with Routes

So far we have been accessing the Controller directly. What if we can create custom URLs that connect to a Controller? That would be interesting right.

Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. Read More @ CodeIgniter.com

Working with Routes in CodeIgniter 4
Working with Routes in CodeIgniter 4
$routes->get('/', 'Pages::index');

In a nutshell, this is what that line of code in the routes.php file means. When a user types in the URL and clicks enter, it hits the routes.php file at first. Then the routes.php file decides to which Controller and which of its functions that the URL and request of resources such as Views should be directed to.

$routes->get(‘<URL>’, ’<CONTROLLER>::<FUNCTION>’);

Accessing the base URL of the application
Accessing the base URL of the application
Adding additional routes
Adding additional routes
$routes->get('(:any)', 'Pages::showme/$1');

We had a Function in the Controller that uses a parameter. If we are to pass parameters via a URL, this should be defined in the routes.php. (:any) refers to the URL accepting a String/Number parameter only. The $1 refers to the parameter being passed to the Controller specific Function. The more the parameters are allowed in an URL, the number of parameters in the routes.php will increase like such $1, $2 and so on.

Testing the routes via the browser by using the parameter as home
Testing the routes via the browser by using the parameter as home
Testing the routes via the browser by using the parameter as about
Testing the routes via the browser by using the parameter as about

Connecting the created Routes to the Navigation

Connecting the created Routes to the Navigation
Connecting the created Routes to the Navigation
<li class="nav-item active">    <a class="nav-link" href="/">Home</a></li><li class="nav-item">    <a class="nav-link" href="/about">About Us</a></li>

Now that we have connected the created routes to the href attribute, we should be able to use the navigation application to move between different views.

Previous

--

--