Tutorial

How To Create a Small Web Application with CakePHP on a VPS (Part 1)

Published on August 23, 2013
How To Create a Small Web Application with CakePHP on a VPS (Part 1)

About CakePHP

CakePHP is a powerful and robust PHP framework built around the Model-View-Controller (MVC) programming paradigm. In addition to the flexible way you can use it to build your application, it provides a basic structure for organising files and database table names - keeping everything consistent and logical.

In the last tutorial we’ve seen how to install CakePHP onto your VPS and do some initial configuration. Additionally, we already set up a database that will serve for our small web application we will start in this tutorial and finish in the next. The purpose is thus to play a bit with CakePHP to better understand how you can use it for building the application you want. We will go through some of the main concepts (Controllers, Models, Views etc) and use examples in order to demonstrate what they are. At the end, we will have a small application that performs CRUD (create, read, update, delete) operations on our database table.

This tutorial assumes that you have followed all the steps covered in the last one. This means having command line access to your own VPS running the LAMP stack and already having installed and configured CakePHP. In other words, it will continue from where the previous tutorial ended.

If you remember, the state of our application was a simple CakePHP installation in the /var/www/project folder and a database called cake which holds a table called posts that currently has one row in it. Let’s get in our mysql command line and add another row:

INSERT INTO posts (title,body,created)
    VALUES ('Another title', 'Another body text', NOW());

Now that we have 2 rows we can go ahead and start using CakePHP to interact with this data. But before, a few words about naming conventions.

Naming Conventions

CakePHP provides some great features if you follow the naming conventions it proposes. This serves well also for keeping your application logic and consistent. For instance, Controller names should be CamelCased, should be in plural, end with the word Controller (for instance PostsController) and be stored in files named the same way (PostsController.php).

Model class names on the other hand are singular and reflect the individual data model (Post). Moreover, the Model class - if named according to convention - will automatically infer that its data resides in the database table called with the same name in plural (posts in this case) and that it will be used by the Controller with the same name in plural and with the word Controller at the end (in our case PostsController).

This is just a short introductory, for more information about conventions in CakePHP, you can visit this page.

The Model

The Model classes are the business layer of your application as they are used to interact with your data. In CakePHP, Models usually represent a database table, but they can also be used for accessing other kinds of data. In this respect, Models are your data models (a blog post, a comment, a user are for instance data models) and their declaration go in files located in the /app/Model folder.

In our application we will follow the naming conventions so we will name our Model class Post and put it in a file called Post.php located in the app/Model folder. This way, it will automatically know that it should use the posts table in our database and will be used by the PostsController.

So let’s go ahead and create the file and place inside the following class declaration by which we extend the default CakePHP Model class to create one for our blog posts (make sure you add the PHP opening tag at the beginning of the file):

class Post extends AppModel {
}

Save the file and exit. By extending the default CakePHP Model class and by following the naming conventions, this is all we need for simple CRUD operations on this table as CakePHP knows what to do. You should know however the method names it uses to query the table so you can actually call them in your Controllers. We’ll go through a few next.

The Controller

The Controller is used to route a user request in the browser to an action in the application. It then interprets the request and makes use of the Models you have to deliver the requested information in a particular format (determined by specific Views).

For our application, we will create a Controller called PostsController in a file called PostsController.php located in the folder app/Controller. We then initially paste in the following code (make sure you add the PHP opening tag at the beginning of the file):

class PostsController extends AppController {
    public $helpers = array('Form');
    
    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }
}

This class extends the default CakePHP Controller class and declares an attribute ($helpers) in which it stores some CakePHP helper libraries that we will use later. Then it creates an index() method (the one that gets called by default if the Controller does not receive directions as to which method to use). Methods in CakePHP are also called actions.

The index() action we just created uses the set() method inherited from the parent Controller to pass data from the Controller to a View (that we will create in a minute). This data is stored in the posts variable and is retrieved from the Post Model that uses the find('all') method to retrieve all the posts from our database table. The reason for which the Model is available to us using $this->Post is because we followed the CakePHP naming conventions.

Now all we have to do is create a View and we will get a page that displays all our posts.

The View

The purpose of the Views are to display the data requested by the Controller and delivered by the Models. Using Views we make sure we keep presentation separate from the business logic of our application. The task at hand now is to create a View file to display the information retrieved by our index() method we declared above.

CakePHP Views are located in the app/View folder inside a folder named after the Controller they belong to. We will then need to put our View file in a folder called Posts and name it index.ctp (after the method requesting it). Inside, let’s place the following code:

<h1>Blog posts</h1>

<?php foreach ($posts as $post): ?>
<p><?php echo $post['Post']['title']; ?> | <?php echo $post['Post']['created']; ?>

<?php endforeach; ?> <?php unset($post); ?>

This will output a very simple and ugly looking page but you’ll get the point. It iterates through the array $posts (that we set and passed in the set() method of the Controller) and outputs the title and creation date of our posts from the table. So to get this information, point your browser to www.example.com/project/posts/index or simply to www.example.com/project/posts (as index() is the default action that gets called if no method is specified).

And as you can see, the application can already perform read operations without you having to write any code for querying the database.

You’ll notice that your data is presented inside the default CakePHP layout (located in app/View/Layouts). All Views are part of layouts and you can create as many as you want. Then all you have to do is specify in your Controller which layout you’ll want to use. We will continue with the default one for the rest of this tutorial as it is used automatically. More information on layouts you can read here.

Now let’s see how we can display an individual post in a separate View.

For this, we’ll need to add another method to the PostsController. So below where you defined the index() method, paste in the following code:

 public function view($id = null) {
        $post = $this->Post->findById($id);
        $this->set('post', $post);
    }

In here, since we are looking for only one post, the Post model will use the findById() method and pass it the ID we want. This ID will come from the view() action that gets a parameter handed to it from the URL in the following way: www.example.com/posts/view/1, 1 being the ID of the post we need. Then the same set() method will pass to the View a variable called post which contains the retrieved post information from the table. Simple. This method contains really the bare minimum at this point. It’s recommended you also implement some checks to see if what gets passed to the Controller is a valid ID etc.

Now let’s create the View itself in the same folder as the one we created earlier, named view.ctp into which we’ll put the following code:

<h1><?php echo h($post['Post']['title']); ?></h1>
<p><small>Created: <?php echo $post['Post']['created']; ?></small></p>
<p><?php echo h($post['Post']['body']); ?></p>

Now if you navigate to www.example.com/project/posts/view/1 you’ll get the post with the ID 1 (the title, creation date and body).

Conclusion

In this tutorial, we’ve seen how to create a basic read operation on our data using CakePHP. We’ve declared a Model class for our data models (the posts), used a Controller to request this data and created a couple of simple Views to display it in the browser. Additionally, we've seen a bit the power of following the naming conventions implemented by CakePHP. Doing so we did not need to write any database queries for our data and the Model, Controller and View got "connected" with ease and without us having to specify too much.

In the next tutorial we will finish our small application by adding the possibility to add posts into the table, edit them and finally delete them.

Article Submitted by: Danny

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
3 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

This comment has been deleted

    i followed the above steps just changed the foldername project with cake but when in the end when i try to open www.example.com/project/posts/index or localhost/cake/posts/index its giving error :- “The requested URL /cake/Posts/index was not found on this server.” And /localhost/cake is working fine as it shows the CakePHP default page. Any help!

    nice tutorial very easy to understand

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel