Uncategorized

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

About CakePHP

CakePHP is a powerful and robust PHP framework based on 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 organizing files and database table names – keeping everything consistent and logical.

In the last tutorial we did we saw how to install CakePHP on your VPS and do some initial configuration. Also, we’ve already set up a database that will serve for our little web application that we’ll start in this tutorial and finish in the next. The purpose, therefore, is to play a little with CakePHP to better understand how you can use it to create the application you want. We’ll go through some of the main concepts (controllers, models, views, etc.) and use examples to demonstrate what they are. At the end we have a small application that performs CRUD (Create, Read, Update, Delete) operations on our database table.

Reading: How to create a website using cakephp

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

If you remember, the status of our application was a simple CakePHP installation in /var/www/project folder and a database named cake containing a table named posts which currently contains one row. Let’s go to our mysql command line and add another line:

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

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

Naming conventions

CakePHP offers some great features if you follow the suggested naming conventions. This is also to keep your application logic and consistent. For example, controller names should be CamelCased, plural, end with the word Controller (e.g. PostsController), and stored in files of the same name (PostsController.php).

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

See also  How to Create a Website Free of Cost?

This is just a short introduction, 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 typically represent a database table, but they can be used to access other types of data as well. In this regard, models are your data models (for example, a blog post, a comment, a user are data models) and their declaration is placed in files located in the /app/Model folder.

See also: How to Start a News Website in 12 Easy Steps

In our application, we follow naming conventions, so we name our model class Post and put it in a file called Post.php, located in the app/Model folder. That way it automatically knows to use the posts table in our database and is used by the PostsController.

So go ahead and create the file and place it in the following class declaration, which we will use to extend the default CakePHP model class to create one for our blog posts (make sure to add the PHP opening tag at the beginning of the file) :

class Post extends AppModel { }

Save the file and exit. By extending the standard CakePHP model class and following the naming conventions, this is all we need for simple CRUD operations on this table as CakePHP knows what to do. However, you should know the method names used to query the table so that you can actually call them in your controllers. Next we’ll go through a few.

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 uses the models you have to provide the requested information in a specific format (determined by specific views).

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

See also  How to Make an App for Both iPhone and Android?

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

This class extends the standard CakePHP controller class and declares an attribute ($helpers) in which to store some CakePHP helper libraries that we will use later. Then it creates an index() method (the one that will be called by default if the controller doesn’t get any instructions as to which method to use). Methods in CakePHP are also known as actions.

The index() action we just created uses the set() method to pass data from the controller into a view (which we’ll create in a moment). This data is stored in the posts variable and retrieved by the Post model, which uses the find(‘all’) method to retrieve all Contributions from our database table. The reason we have the model available to us with $this->Post is that we followed CakePHP naming conventions.

Now we just need one Create view and we get a page that shows all our posts.

The view

The purpose of the views is to show the data requested by the controller and provided by the models. By using views we ensure that we keep the 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 declared above.

CakePHP views reside reside in the App /View folder within a folder named after the controller they belong to. We then need to put our view file in a folder called Posts and name it index.ctp (after the method that requests it). Let’s place the following code in it:

&lth1>Blogposts&lt/h1> &lt?php foreach ($posts as $post): ?> &ltp>&lt?php echo $post[‘Post’][‘title’ ]; ?> | &lt?php echo $post[‘post’][‘created’]; ?> &lt?php unset($post); ?>

See also: How Long Does It Take To Design A Logo?

This will output a very simple and ugly looking page, but you’ll get the point. It loops through the $posts array (which we set and passed in the controller’s set() method) and prints 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 just www.example.com/project/posts ( as index() is the default action, which will be called if no method is specified).

And as you can see, the application can already perform read operations without any code need to write to query the database.

You’ll notice that your data is presented in the standard CakePHP layout (found in app/View/Layouts). All views are part of layouts and you can create as many as you like. Then all you have to do is specify in your controller which layout you want to use. We will continue with the default setting for the rest of this tutorial as it will be used automatically. You can read more about layouts here.

See also  How is the value of my car determined?

Now let’s see how we can display a single post in a separate view.

To do this, we need to add another method of PostsController. So, below where you defined the index() method, add the following code:

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

Since we’re only looking for a post here, the Post model uses the findById() method and passes it the desired ID. This ID comes from the view() action, which takes a parameter from the URL in the following way: www.example.com/posts/view/1 , where 1 is the ID of the post we need. Then the same set() method will pass a variable called post to the view containing the retrieved post information from the table. Simply. This method really contains the bare minimum at this point. It is recommended that you also implement some checks to see if what is being passed to the controller is a valid ID etc.

Now let’s create the view itself in the same folder as the that we created earlier, named view.ctp, in which we paste the following code:

&lth1>&lt?php echo h($post[‘Post’][‘ title’]); ?>&lt/h1> &ltp>&ltsmall>Created: &lt?php echo $post[‘post’][‘created’]; ?>&lt/small>&lt/p> &ltp>&lt?php echo h($post[‘Post’][‘body’]); ?>&lt/p>

If you go to www.example.com/project/posts/view/1 you will get the post with ID 1 (title, creation date and body).

Conclusion

In this tutorial we have seen how to create a basic read operation for our data using CakePHP. We declared a model class for our data models (the posts), used a controller to request this data, and created a few simple views to display in the browser. Additionally, we’ve seen a bit of the power of following the naming conventions implemented by CakePHP. This meant we didn’t have to write any database queries for our data, and the model, controller, and view were “connected” with ease and without us having to specify too much.

In the next tutorial, we’ll finish our little application , adding the ability to add, edit and finally delete posts in the table.

See also: How To Send Mass Email In Outlook | Step-By-Step [2023]

.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button