Hướng dẫn học : Tạo giỏ hàng với Cakephp

Hướng dẫn học : Tạo giỏ hàng với Cakephp

1 .Giới thiệu

Bài viết gói gọn trong một số chức năng chính :

  • Hiển thị sản phẩm
  • Chọn sản phẩm cần mua để thêm vào giỏ hàng
  • Cập nhật giỏ hàng

Các chức năng trên nếu chúng ta chịu khó thì cũng có thể tự viết được . Nhưng Plugin CakePHP-Cart này còn có còn có một số chức năng như thanh toán PayPal , Order sản phẩm . Nếu bạn nào có hứng thú có thể tìm tự hiểu thêm về nó nhé . Có thể khai thác sâu hơn trong đường link dẫn tới mã nguồn của Plugin CakePHP-Cart

Mã nguồn https://github.com/ProLoser/CakePHP-Cart

2. Viết chức năng :

2.1 Chuẩn bị CSDL :

Tạo table products

CREATE TABLE `products` (

  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) DEFAULT NULL,
  `description` varchar(255) NOT NULL,
  `price` int(11) NOT NULL,
  `status` enum('inactive','active') NOT NULL DEFAULT 'active',
  `taxable` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
 
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `products` VALUES ('1', 'T-shirt', null, 'Model wears: UK 8/ EU 36/ US 4\r\nModel\'s height: 175 cm/5\'9\"', '230000', 'active', null);
INSERT INTO `products` VALUES ('2', 'Jumpsuit', null, 'Model\'s height: 175 cm/5\'9\"', '320000', 'active', null);
INSERT INTO `products` VALUES ('3', 'Blazer With Sequin Sleeves', null, 'Model\'s height: 175 cm/5\'9\"', '500000', 'active', null);
INSERT INTO `products` VALUES ('4', 'Skinny Jeans with Foil Snake ', null, 'Skinny Jeans with Foil Snake ', '400000', 'active', null);
INSERT INTO `products` VALUES ('5', 'Midi Dress in Mesh Spot', null, 'Midi Dress in Mesh Spot', '190000', 'active', null); 

2.2 Tạo Component Shopping Cart :

Vào app/controllers/components/ tạo file shopping_cart.php
Download Component Shopping Cart tại đây : shopping_cart.rar

2.3 Tạo Controller Product :

Vào app/controllers/ tạo file products_controller.php với nội dung sau

<?php
class ProductsController extends Controller{
    var $name = "Products";
    var $uses = array("Product");
    var $components = array("ShoppingCart");
 
    function index(){
        $this->set("cart",$this->ShoppingCart->getOrderDetails());
        $this->set("data",$this->Product->find("all"));
 
    }
 
    function view(){
 
        $pid = $this->passedArgs['id'];
        $this->set("data",$this->Product->find("first",array("condition"=>array("id"=>$pid))));
    }
}

Controller Products này có 2 chức năng chính là :

- Liệt kê sản phẩm và giỏ hàng (nếu có chọn mua) : thể hiện trong function index()
- Xem chi tiết sản phẩm : thể hiện trong function view()
- Lấy thông tin của giỏ hàng : $this->ShoppingCart->getOrderDetails() , thông tin này được lưu dưới dạng Session .

2.4 Tạo file view cho function index() , vào app/views/ tạo thư mục products/ , tạo file index.ctp với nội dung sau :

<?php echo $this->element("navigate");?>
<div id="product" style="width: 800px;float: left;">
    <h1>List product</h1>
    <div id="list_product">
        <table>
            <thead>
                <th>Name</th>
                <th>Price</th>
                <th>Status</th>
                <th>&nbsp;</th>
            </thead>
            <tbody>
            <?php
            if($data!=NULL){
                foreach($data as $item)
                {
                    echo "<tr>";
                    echo "<td>".$this->Html->link($item['Product']['name'],array("controller"=>"products","action"=>"view","id"=>$item['Product']['id']))."</td>";
                    echo "<td>".$item['Product']['price']."</td>";
                    echo "<td>".$item['Product']['status']."</td>";
                    echo "<td>".$this->Html->link("Buy",array("controller"=>"carts","action"=>"additem","pid"=>$item['Product']['id']))."</td>";
                    echo "</tr>";
                }
            }
            ?>
            </tbody>
        </table>
    </div>
</div>
<!-- Carts -->
<div id="cart" style="width: 400px;float: left;">
    <?php
    if($cart['LineItem']!=NULL){
        echo "<ul>";
        $num_item = 0;
        foreach($cart['LineItem'] as $item){
            echo "<li><span style='color:red'>".$item['Product']['name']."</span> : <span style='color:blue'>".$item['Totals']['quantity']." Item</span></li>";
            $num_item +=$item['Totals']['quantity'];
        }
        echo "</ul>";
        echo "Total Item : ".$num_item."<br/>";
        echo "Total Price : ".$cart['Totals']['total'];
    }
    ?>
</div>
<!-- Debug -->
<div id="debug" style="width: 800px;float: left;">
   <?php //debug($cart); ?>
</div>

2.5 Tại thanh navigation :

Thanh navigation có các chức năng sau :
- Hiển thị sản phẩm
- Xem giỏ hàng
- Xóa giỏ hàng

Ta vào app/views/elements/ tạo file navigate.ctp với nội dung sau

<ul id="navigate">
    <li><?php echo $this->Html->link("List Product",array("controller"=>"products","action"=>"index"));?></li>
    <li><?php echo $this->Html->link("View Cart",array("controller"=>"carts","action"=>"index"));?></li>
    <li><?php echo $this->Html->link("Del Cart",array("controller"=>"carts","action"=>"destroy"));?></li>
</ul>

file navigate.php được gọi trong file index.ctp thông qua đoạn mã

<?php echo $this->element("navigate");?>

Đương nhiên là ở bất cứ file view nào khi muốn hiển thị nội dung của file navigate.ctp ta điều dùng đoạn mã trên

2.6 Tạo file view cho function view() của Controller Products , vào app/views/products/ tạo file view.ctp , có nội dung như sau :

<?php echo $this->element("navigate");?> 
<h2><?php echo $data['Product']['name'];?></h2>
<h1><?php echo $data['Product']['description'];?></h1>
<h3><?php echo $data['Product']['price'];?></h3>
<h4><?php echo $data['Product']['status'];?></h4>

2.7 Tạo Controller Carts : ta vào app/controllers tạo file carts_controller.php

<?php

class CartsController extends Controller{
    var $name = "Carts";
    var $uses = array("Product");
 
    var $components = array('ShoppingCart');
 
    /**
     * Show detail Cart
     */
    function index(){
        $this->set("cart",$this->ShoppingCart->getOrderDetails());
    }
 
    /**
     * Add item to Cart
     */
    function additem(){
        $pid = $this->passedArgs['pid'];
        if(isset($pid))
        {
            $this->ShoppingCart->addItem($pid);
        }
        $this->redirect(array("controller"=>"products","action"=>"index"));
    }
 
    /**
     * Del Item
     *
     */
    function delitem(){
        $pid = $this->passedArgs['pid'];
        $this->ShoppingCart->removeItem($pid);
        $this->redirect(array("controller"=>"carts","action"=>"index"));
    }
 
    function update(){
        if(isset($_POST['update'])){
            $qty = $_POST['qty'];
 
            foreach($qty as $key=>$value){
 
                    $this->ShoppingCart->updateItem($key,0,$value);
 
            }
        }
        $this->redirect(array("controller"=>"carts","action"=>"index"));
    }
    /**
     *
     * Delete all products selected
     */
    function destroy(){
        $this->ShoppingCart->resetCart();
        $this->redirect(array("controller"=>"products","action"=>"index"));
    }
}

Controller này có một số chức năng tương ứng với hàm :

- index() : xem chi tiết giỏ hàng bạn đang có
- additem() : thêm sản phẩm vào giỏ hàng
- delitem() : xóa sản phẩm khỏi giỏ hàng
- update() : cập nhật giỏ hàng
- destroy() : Xóa toàn bộ giỏ hàng

2.8 Tạo file view khi xem chi tiết giỏ hàng : vào app/views/ tạo thư mục carts/ rồi tạo file index.ctp với nội dung sau

<?php echo $this->element("navigate");?>

<div id="product" style="width: 800px;float: left;">
    <h1>Your Cart</h1>
    <div id="list_product">
        <table>
            <thead>
                <th>Name</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>&nbsp;</th>
            </thead>
            <tbody>
            <?php echo $this->Form->create(null,array("url"=>"/carts/update")); ?>
            <?php
            if($cart['LineItem']!=NULL){
                foreach($cart['LineItem'] as $key=>$item)
                {
                    echo "<tr>";
                    echo "<td>".$this->Html->link($item['Product']['name'],array("controller"=>"products","action"=>"view","id"=>$item['Product']['id']))."</td>";
                    echo "<td>".$item['Product']['price']."</td>";
                    echo "<td><input size='3' name='qty[".$key."]' value='".$item['Totals']['quantity']."'</td>";
                    echo "<td>".$this->Html->link("X",array("controller"=>"carts","action"=>"delitem","pid"=>$item['Product']['id']))."</td>";
                    echo "</tr>";
                }
                echo "<tr>";
                echo "<td>Total</td>";
                echo "<td></td>";
                echo "<td colspan='2'>".$cart['Totals']['total']."</td>";
                echo "</tr>";
 
                echo "<tr>";
                echo "<td colspan='3'></td>";
                echo "<td ><input type='submit' name='update' value='Update' /></td>";
                echo "</tr>";
            }
            ?>
            </form>
            </tbody>
        </table>
    </div>
</div>
<!-- Debug -->
<div id="debug" style="width: 800px;float: left;">
   <?php //debug($cart); ?>
</div>

2.9 Chạy thử ứng dụng :

2.9.1 Hiển thị sản phẩm : http://localhost/cakephp_cart/products

2.9.2 Sau khi chọn mua sản phẩm

'

2.9.3 Chọn xem giỏ hàng : http://localhost/cakephp_cart/carts

2.9.4 Cập nhật giỏ hàng

2.9.5 Xóa sản phẩm khỏi giỏ hàng

2.9.6 Debug xem thông tin giỏ hàng :

Chúng ta có thể vào file view index.ctp trong thư mục app/views/carts/index.ctp , tìm dòng

<?php //debug($cart); ?>

Thay là

<?php debug($cart); ?>

Bạn thấy được thông tin của giỏ hàng dưới dạng array như hình bên dưới .

Dữ liệu được hiển thị được lấy từ hàm : $this->ShoppingCart->getOrderDetails() trong Controller Carts (app/controllers/carts_controller.php)

Ngoài ra còn có một số Plugin Shopping Cart như :

1. VaM Cart
2. ShoppingCart plugin for CakePHP (techno-geek Shopping Cart)
3. cakecart
4. bakesale Shopping cart
5. CakePHP-Cart
6. Flashub.com
7. kaching-php

Bài viết trên tôi chọn CakePHP-Cart bởi vì code viết dễ hiểu , tôi cảm thấy đọc và có thể tích hợp vào web một cách dễ dàng  , Tuy nhiên các bạn cũng có thể khai thác và tìm hiểu các Plugin khác , không nhất thiết phải sử dụng CakePHP-Cart

Tags: 
Bạn thấy bài viết này như thế nào?: 
No votes yet
Ảnh của Khanh Hoang

Khanh Hoang - Kenn

Kenn is a user experience designer and front end developer who enjoys creating beautiful and usable web and mobile experiences.

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Vietnam Digital SEO Summit 2019 thu hút gần 1.000 người tham dự

Vietnam Digital SEO Summit 2019 tại Trung tâm hội nghị triển lãm White Palace, TP.HCM.

Ngày 06 và 07-7 vừa qua, sự kiện Vietnam Digital SEO Summit 2019 đã diễn ra tại Trung tâm hội nghị triển lãm White Palace, TP.HCM.

Apple phát hành bản cập nhật Java

Apple phát hành bản cập nhật Java

Java cho Mac OS X 10.7 Update 1, phát hành hôm thứ 3 ngày 8/11, cập nhật phần mềm cho phiên bản 1.6.0_29, và cung cấp một số cải thiện về độ tin cậy, bảo mật, khả năng tương thích cho người dùng Mac OS X Lion.

Seo top

Bài 1: Bắt đầu kiếm tiền với Google Adsense

Trước kia mình từng nghĩ rằng kiếm tiền với Google Adsense là một điều vô cùng khó khăn. Để có thể kiếm được tiền, bạn cần có một trang web phát triển lớn mạnh và lâu năm. Như vậy mới có đủ lượng khách truy cập cần thiết mỗi ngày click vào quảng cáo Google Adsense để sinh lợi nhuận.

Công ty diệt chuột T&C

 

Diet con trung