CodeIgniter 4 and PHP MVC basics: controllers, views and layouts

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
with the codeigniter framework installed when we open the site in a browser we see this page however if we look at the code for this page index.php in the public folder there's lots of php code but no html and certainly none of the content that we see in the browser so what's happening in this section we'll find out we'll learn the basics of mvc frameworks and how to display a page of html using codeigniter in a traditional php website without a framework you create php files that you request directly in the browser with the file name in the url if you have files in subfolders then you just include that subfolder before the file name as part of the url so the url corresponds directly to the file structure of your web server codeigniter is different codeigniter is a model view controller or mvc framework instead of having your code in files that you open directly in the browser you organize your code into models views and controllers models deal with data for example storing it and retrieving it from a database views contain the code that the user sees in the browser for example html and controllers decide which view to load which model to use and so on when a request comes in from the browser the framework decides which controller to run based on the url and sends that controller's response back so in an mvc framework the url doesn't correspond directly to files and folders on the web server the index.php page in the root of the site is called a front controller this loads the framework this is part of the framework so you don't need to change any of the code in here instead all your code goes in the app folder and its subfolders we'll cover what each of these subfolders is throughout the course let's start with controllers in the controllers folder let's open the home controller this is simply a class that extends the base controller class and it has a single public method called index let's remove its contents for now and replace it with a simple echo statement that prints out the message hello world in the browser we see that message displayed so when we go to the root of our site the framework executes this method inside this class and we see the results in the browser we just printed out this message by changing the code in this controller method we don't want to output content directly like this inside a controller though one of the advantages of using an nvc framework is that the presentation code for example html is separated from the application code in an mvc framework we put presentation code in a view views go in the views folder this welcome message.php file is the page we saw when we first loaded the framework we don't need this now so you can safely delete it let's create a view for the home page of our site inside the views folder you're free to organize view files however you like however it's good practice to create a subfolder for each controller's views as we're going to load this view from the home controller we'll create a subfolder of the views folder called home it's also good practice to match the name of the view file to the name of the method in the controller our homepage method is called index so let's create a new file called index.php a view is just a file that contains html or whatever you want to send to the browser so let's add some basic html in here with a doctype a head a body and so on in the controller let's remove this echo line and to display the view file from the controller we call the view method passing in the path to the file inside the views folder this returns a string so we can just echo that out directly in the browser now we see the contents of the view file we just added the view function loads the contents of the file and returns it as a string this function isn't part of standard php it's part of the codeigniter framework it's inherited from the parent controller so when we create a controller class by extending this base controller class we get access to the various framework functions we need when calling this method the view filename extension in this case.php is optional so you can remove it if you like and in the browser it still works we just added a view file that's displayed when we go to the root of our site we're loading this view and echoing its contents out in the home controller but how does the framework know to run this controller method the framework uses a component called a router to decide which controller and method to run based on the url the router contains various rules or routes which map urls to controllers and methods urls in codeigniter are split into segments separated by slashes by default the first segment represents the controller class the second segment represents the method inside that class and any other segments are arguments to that method so on our site if i change the url to slash home slash index it still works home is the controller and index is the method we configure routes in the routes configuration file in the app folder in the config subfolder this file is called roots.php the default behavior that we just saw of the first segment being the controller the second segment being the method and so on is enabled by this setting set auto route to true unless you have a good reason to do so i recommend you leave this set to true as it means most urls will just work without you having to add a route for each one this is what lets us access our home page with home slash index in our url there are also settings here for the default controller which is set to home and the default method which is set to index so as index is the default method we can remove this from the url and it still runs the index method the same for the controller name this is home by default so we can remove this too and it still runs the index method in the home controller there's also a specific route set in here which maps the home page represented by a single forward slash the index method in the home controller as we have the default set above this line isn't really necessary but having it does give a slight performance increase for the home page we'll look at routing in more detail later on let's add a new controller so we'll create a new file in the app controllers folder this is going to display a list of tasks so let's call it tasks.php make sure you start the file name with a capital letter we'll start by copying the code from the home controller and pasting this in the new file by default controller classes are in the app controller's namespace so we'll leave that as it is apart from putting it on a new line so it's clearer we'll change the name of the class to tasks the php standard for class names is to start them with a capital letter and as we created the file with the same name as the class this file will be loaded automatically when we first use it in the index method it will show the home index view so if we go to slash tasks slash index in the browser we see the home index view let's add a view for the tasks index first we'll create a subfolder in the app views folder that matches the name of the controller tasks then we'll create a new file in here called index.php for the content let's copy the html from the home index view and paste it in the new file for now we'll simply change the content of the header element to tasks then in the tasks controller we'll change this line so we're displaying the tasks index view instead in the browser now we see the content from the tasks index view file the framework has routed this url to the new controller and run this method also as we saw earlier index is the default action so we can remove index from the url and this works as well at the moment we have two views one for the tasks index and one for the home index we're repeating ourselves though with the top part of this code the doctype head section and opening body tag repetition like this isn't a good idea as if we ever want to change this section we need to do it in more than one place so let's extract this out to a separate view file first we'll copy this then we'll create a new file in the app views folder and call it header.php note how this isn't in a subfolder of the views folder and we'll paste the code we just copied in here in the home index file we can now remove this header code and then in the home controller we're already printing out the contents of the index file to output the header we'll call the view function again passing in the path to the header view we just created in the browser the home page looks the same and the source includes all the html as before only now we split it up into two files this is one way to deal with repeated view code calling the view function multiple times in a controller method like this this was common in earlier versions of codeigniter it does mean the controller code is somewhat bloated though and you have to remember to include the header wherever you display a view another way to include common code would be to include one view inside another for example here in the tasks index we still have the header code let's delete this and include the header view here directly rather than just a regular php include we do this using codeigniter's include method which means we can access any codeigniter functions inside the included view if necessary so let's add a call to that method passing in the path to the file we want to include in the browser if we go to the tasks index the file is shown as before including the header this technique is fine if you want to include a view file on some pages but not on others for code that's shared among every page though it's not ideal as again you have to remember to include it in every single view calling the view function more than once in the controller also isn't ideal as we just saw with the latest version of codeigniter there's a better way to do this if you have view code that's common to all pages or view code that's common to a group of several pages then the simplest way to avoid repeating this code is to use a view layout view layouts allow us to create views that we can extend much like a class extending another so we can have a base view that contains common code and any view that wants to include this common code simply extends the layout view let's create a view layout that includes this common header code first let's create a subfolder of the views folder called layouts it isn't required that view templates are put in this folder but it's good practice to keep the views folder organized in here let's create a new file and call it default.php you can call view templates whatever you like in the header view that we created earlier let's copy this code and paste it in the new layout file let's also add the code that's common at the end of each view the closing body tag and closing html tag to make this into a template we add one or more sections to display a section we call the render section method passing in the name of the section the name is a simple string and can be whatever you like i've called this one content now we can use this layout in an existing view for example here in the home index view to use a view layout we call the extend method at the top passing in the path to the view template inside the views folder then all content in a view that extends a layout needs to be inside a section we enclose content inside a section by calling the section method before it passing in the name of the section which i called content and the end section method after it we don't need to pass in the name of the section when we end it as the code knows which section we're ending as the layout includes these closing tags we can safely remove them finally in the home controller we can remove this line where we're echoing out the header file as the header code is now part of the layout in the browser the home page works as before with the header and end closing tags where they should be so the individual view is much simpler and we only need one view call in the controller let's add another section to the view layout we just created you can have as many sections as you need we want the title to be different on each page so let's replace this hard-coded title with a section called title then in the home index file to add content for this section first we call the section function as before passing in the name of the section in this case title then the content we want in that section which is the string home and then the end section function you can call the functions on the same line like this are on separate lines as below depending on the content of the section in the browser the title of the page is now set by the section we just added let's change the tasks index to use this layout too first let's remove this line where we're including the header and also the closing tags at the bottom then we can copy the first three lines of the home index view and paste them at the top of the tasks index let's change the content of the title section and then we just call end section at the end to end the content section in the browser now if we go to the tasks index we see the title we just added and the content is included inside the layout code using a view layout is the simplest way to include common code in several views now we're not using this header file anymore we can delete it one final thing we need to do in the controllers is to return the content instead of printing it out directly using echo it's not good practice to print out content directly like this from a controller instead we'll return it and the framework will take charge of outputting it likewise in the tasks controller we'll change this echo to return we'll see later on how we can return different types of response and not just content and in the browser nothing has changed the view that we load from the controller is still displayed
Info
Channel: Dave Hollingworth
Views: 13,094
Rating: undefined out of 5
Keywords:
Id: c8zHxE-mN4c
Channel Id: undefined
Length: 24min 50sec (1490 seconds)
Published: Sat Nov 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.