CakePHP - Building Your First Site

in utopian-io •  7 years ago  (edited)

What Will I Learn?

In this tutorial we will be covering the basics of a Cake application, resulting in our "Hello World" example.

Requirements

CakePHP 3.5 https://cakephp.org/

Difficulty

Intermediate

Tutorial Contents

  • Creating a Model
  • Creating a Controller
  • Creating a View

CakePHP - Building Your First Site

In this tutorial we will be covering the basics of a Cake application, resulting in our "Hello World" example.

The first thing to remember is that Cake is a PHP framework that follows the Model-View-Controller standard, which helps us separate our application layers quite nicely. It adds a couple more files and folders, but it is quite worth it in the end. The MVC convention is becoming a more and more common concept, especially among web applications. 

Another important thing to point out is that Cake also follows the Convention-Over-Configuration methodology, which can greatly reduce the amount of code you have to write. In a nutshell, for bakers like us, if we name things the right way, Cake will automatically grab everything for us. This makes cake simple to use, but powerful all at the same time, with minimal configuration needed. 

Creating a Model

Now down to business. We are going to need to start by creating a model that will correspond to our table in the database. Typically, one table means one model, with the name of the model reflecting the table it corresponds to. In the case of Cake, your table names should always be plural (as in Products), and your model names should be singular. Following this convention, we need to create a Product.php in the directory cake_root/app/models folder.

Once you have a new blank PHP file, it is time to write some code. In Cake, a model in it's simplest form is a PHP class declaration. All models must be children of the Cake AppModel class, and for now our class will have one variable, a name. This is not necessary, but over time I have noticed that it is good common practice to define it, just in case. Our Product.php file will look like this:

<?php
class Product extends AppModel
{
 var $name = "Product";  
}
?>

A model is responsible for one thing, grabbing data. While this can be complicated at times, that is still all a model does. You will notice that our model is actually a PHP class, named the singular version of our table name. Our actual name variable just helps us make sure that the variable passed to our controller is the correct name, mainly a precaution I have found useful. The last thing we want is a variable named something we don't know. Once the data is collected, it is all passed to the appropriate controller, which at this point we have to create.

Creating a Controller

Cake controllers are named by taking the table name and adding "controller" to it. In the case of file names, you add an underscore in between. So our controller file would be named products_controller.php. All controllers are going to be in the directory cake_root/app/controllers, so go ahead and create the file in there. Once the file is created, we can start coding our controller.

Just like models, we need to define a class that is a child of the AppController class in order for your controller to work. But unlike models, there is a lot more to define in a controller. First off, controllers take the data given to it by the model, processes it, then routes it to a view for display. The more data you have, and the more complex your application needs to be, the more complex your controllers get. A vital part of each controller are the functions that are declared in the controller class. Each function corresponds to a different display for that data. For this tutorial, we are keeping it simple and working with the index() function. This function corresponds to a root view, just like in a normal web page.

Inside this function we need to grab our data, and then pass it to our view. The data is not automatically passed to the view, so we are going to use a very simple and basic Cake controller method called set(). The Set() function sets a variable to the data you provide, which is then passed on to the view. For this simple tutorial, we are going to take all the data from our table and pass it on. In order to grab our data, we use the controller method find(). Our code would look something like:

<?php
class ProductsController extends AppController
{
 var $name = "Products";
 function index()
 {
 $Data = $this->Product->find('all');
 $this->set('Data', $Data);
 }
}
?>

The first thing you may notice is that the name has no underscore, which is part of the class naming convention. The file name will have one, but it is omitted in the class name. Next we have the name variable, which just like the model, it is there just as a precaution. After we define the name, we have to define our first function, which in this case we are defining the index() function. Inside this function we are doing 2 things: collect all of our data from our products table using the Product "magic variable", then setting a Data variable to pass on to the view.

Cake's page routing works from the url of the page, using mod_rewrite to display the appropriate page content. In the strictest sense, a CakePHP application will use the following decoding to display the page content: http:www.somesite.com/cake_root/controller/method/method argument. By defining the index method, we are saying that the default for the controller is to do whatever is in the method. So in order to use our new controller, all we would have to do is http://localhost/cake_root/products. If you try that now, however, the error message won't be pretty. Before we can see anything, we must define the index view.

That Nasty 'No View' Error Message

Creating a View

A view is simple, but yet can be complex. A view takes the information based by a controller, and displays it. While it sounds simple, it can get a little crazy. First, we need to create a view file. Going through the Cake directory, you may have noticed the /app/views folder. Inside this folder, each controller gets its own folder, then each controller folder is filled with views, named based on the methods in that controller. So, our file would be cake_root/app/views/products/index.php. When your file is created, go ahead and open it up.

One thing to remember is that views are never full HTML files. They are always wrapped in what is called a layout. The layout is the base page that is usually displayed, and is static from page to page. Things like a header, sidebar, and footer are all examples of things a layout may hold. Views also have no fancy classes, methods, or variables, they just output stuff to the page. For our index page, all we will do at this point is dump our data to the page. Personally, I do this with PHP's print_r() method, which just prints an array. In order for this to work in HTML, you have to use <pre>tags. So, our view will be short and sweet:

<pre>
<?php print_r($Data) ?>
</pre>

This view completes our MVC hierarchy, thus allowing us to have our first Cake page up and running. If you browse to http://localhost/cake_root/products, you should see our products data, along with a Cake generated query table which just shows us all the queries that were made in the process. 

This is pretty much the simplest page you can get with CakePHP, and can be considered the equivalent to a "Hello World." All our application does right now is take the products data, passes it to the view, which in turn displays it.



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @cues I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x