There are plenty of open source shopping cart in the market right now. However we think it is important for a developer to understand how a shopping cart works.
In this series we are going to build a simple shopping cart using CakePHP and jQuery. Please note, we focus on building the common functions of a shopping cart using CakePHP, such as adding product to shopping cart, removing product to shopping cart as well dynamically update shopping cart using ajax. Its purpose is to demonstrate the basics of building a shopping cart. Hence it is not a production ready piece; there are lots of features you need to add before it goes live for production.
This series is for beginners who are learning CakePHP. Let us get started.
Download link of entire source code is provided in part 2 of this series.
Design a very simple database table "products" as below. It stores products' information. The idea here is to demonstrate how CakePHP Model works with database table.
Import the database table via following codes:
CREATE TABLE products ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(250) NOT NULL, price FLOAT NOT NULL, image VARCHAR(250) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Insert some sample products data as well. As you can see, we are not going to build a backend system to manage products in this series. Some sample products data are needed.
INSERT INTO `products` (`id`, `name`, `price`, `image`) VALUES (NULL, 'Samsung Galaxy S4', '600', '/img/s4.jpg'); INSERT INTO `products` (`id`, `name`, `price`, `image`) VALUES (NULL, 'Samsung Galaxy Note 3', '500', '/img/note3.jpg'); INSERT INTO `products` (`id`, `name`, `price`, `image`) VALUES (NULL, 'Samsung Comment 3', '400', '/img/comment.jpg');
In this step, we will place Bootstrap resources accordingly to CakePHP application.
Now the "app/webroot" directory should look similar as below:
The highlighted parts are what we have added.
Now if you navigate to the installed CakePHP application, you should view a simple page as below, which indicates CakePHP has been installed properly.
After editting, "app/View/Layouts/default.ctp" should look like below:
You have probably noticed, this is a very simple layout file. It has a top navigation bar with a content area. Pay attention to the right corner shopping cart icon. We have assigned an element ID "cart-counter" to it. We will use this ID to identify and update its value later in the application.
Now the application's default page should look alike below:
In part 2 of this series. We are going to implement the core part of shopping cart. Displaying products from database, adding product to cart as well as updating shopping cart. Stay tuned!
Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.