Building A Simple Web App Using CodeIgniter 4 - Part 2 | MVC Basics
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.
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
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
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.
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.
//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.
If we look closely, the Environment has switched from production to development and the debug console has been activated.
Glimpse of one of the debug console tabs Vars which shows View Data, Session User Data, Request etc.
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
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';}
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.
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.
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.
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.
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.
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”
Views -> pages-> RMB -> New File -> Create 2 files called “about” and “home”
Views -> RMB -> New Folder -> Create a Folder called “templates”
Views -> templates-> RMB -> New File -> Create 2 files called “header”and “footer”
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.
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.
<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.
</body></html>
Building the Views using Bootstrap 4
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<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>
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.
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.
Now if we access the controller using,
http://localhost:<PORT>/<CONTROLLER>/<FUNCTION>/<PARAMS>, we should be seeing something like this.
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.
// 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.
Continuing to enhance the User Interface using Bootstrap 4…
<section></section>
Try Editing the home.php View by yourself to get an output like this at the end.
<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>
Adding a Navigation bar using Bootstrap 4
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
$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>’);
$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.
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.