Tạo giỏ hàng theo mô hình MVC

Hôm nay mình xin hướng dẫn các bạn tạo giỏ hàng theo mô hình MVC. Giỏ hàng này các bạn cũng thường thấy trong các trang web bán sản phẩm đúng không nào. thiết kế được một giỏ hàng tương đối rất là khó. cả chính tôi khi bắt đầu thiết kế một giỏ hàng thôi mà tôi cảm thấy ôi khó thê. nhưng từ từ các bạn sẽ nắm bắt được cách làm của nó thôi, hãy cùng làm theo tôi nào.

các bạn cũng biết muốn viết được mô hình MVC thì các bạn cũng phải biết chút ít về nó nhé. ở đây tôi tạo 4 thư mục:
+ config: chứa file dbcon.php(đây là file khai báo kết nối đến database)
+controllers: chứa file controllers.php, giohang.php, product.php( 3 file này là nằm trong demo mà mình đã tạo)
+model:chứa file model.php(đây là file để nhận yêu cầu từ controllers gửi qua để bắt đầy xử lý.
+view: chứa file cart-template.php, viewCart-template.php( 2 file này dùng để hiện các sản phẩm mà ta muốn đưa ra)
- cuối cùng là ngoài thư mục các bạn tạo một file index.php cùng cấp với 3 thư mục trên. khi chạy demo thì file index.php này sẽ chạy đầu tiên.

còn đây là csdl tùy theo bạn các bạn muốn csdl thế nào các bạn thiết kế như vậy nhưng các bạn muốn chỉnh sử theo ý của bạn thì vào code model.php chỉnh lại table mà bạn cần truy vấn, và dbcon.php chỉnh sửa lại database mà bạn đã thay đổi. nói chùng là tuy các bạn thiết kế nhé.

code sql


	
CREATE TABLE IF NOT EXISTS `maytinh` (

	
`idmt` int(100) NOT NULL AUTO_INCREMENT,

	
`hieu_mt` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

	
`ten_mt` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

	
`gia` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

	
`hinh_mt` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

	
PRIMARY KEY (`idmt`)

	
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;


Tiếp theo các bạn tạo một file dbcon.php(đây là file kết nối) trong file này các bạn ghi như sau:

<?php
$db_localhost='localhost';

$db_username='root';

$db_password='';

$db_database='banghang';
?>

sau khi tạo file kết nối các bạn tiếp tục tạo file index.php đây là file giao diện chính của chúng ta.

code cua file index.php

//tạo file index.php
<?php
require 'controller/controller.php';
ob_start();
session_start();</em>
?>
<!DOCTYPE html>
<html>
<head>
<meta https-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Shoping cart</title>
</head>	
<body>	
<?php
if(isset($_GET['action'])=='cart'){	
	include_once 'view/viewCart-template.php';	
}	
else{
	$checkcart = 1;	
	if (isset($_SESSION['cart'])){	
		foreach ($_SESSION['cart'] as $k => $v) {	
			if (isset($v)){
				$checkcart = 2;
			
			}
		}	
	}
	if ($checkcart != 2){	
		echo "Giỏ hàng của bạn: <strong>0 Sản Phẩm</strong>";	
	}
	else{
		echo "Giỏ hàng của bạn: <strong>".count($_SESSION['cart'])." Sản Phẩm</strong><a href='".$_SERVER['PHP_SELF']."?action=cart'>Giỏ Hàng</a>";
	}	
}
	include_once 'view/cart-template.php';

?>

	
<?php
	
if (isset($_GET['addcart'])){
	
	$cart_sp->addCart($_GET['addcart']);
		
	echo "<script>window.history.back();</script>";
	
}

	
if (isset($_GET['xoa'])){
	$cart_sp->xoaCart($_GET['xoa']);	
	echo "<script>window.history.back();</script>";
	
}
	
if (isset($_GET['xoahet'])){

	unset($_SESSION['cart']);
	echo "<script>window.history.back();</script>";
	
}
	
if (isset($_POST['update'])){
	$cart_sp->capnhatCart();
	
}

?>
</body>
</html>

Controllers

- Tại file giohang.php

code giohang.php

<?php	
class giohang{	
	public $id,$tensanpham,$gia,$soluong;	
	public function __construct($pid,$ptensanpham,$pgia) {
	$this->idmt = $pid;
	$this->ten_mt = $ptensanpham;
	$this->gia = $pgia;
	$this->soluong = null;
   }
}
	
?>

- Tiếp tục tạo file product.php

code product.php

<?php

class product {
	public $id,$tensanpham,$gia;
	function __construct($pid,$ptensanpham,$pgia) {
		$this->idmt = $pid;	
		$this->ten_mt = $ptensanpham;
		$this->gia = $pgia;
	}
}

?>

Tiếu tục bạn tao file controller.php

code controller.php

<?php

include_once('model/model.php');

include_once('product.php');

include_once('giohang.php');
	
class cart{
	
public $id,$tensanpham,$gia;
	
private $soluong=null;

public $model;
	
public $product;

public function __construct(){	
	$this->model=new model();
 }

	
public function viewAllsanpham(){

	$sql="select * from maytinh";

	$this->model->select($sql);
	
	$a_data=$this->model->fetchArray();

	$mangsplist=array();

	foreach ($a_data as $value) {
		
		$sp=new product($value['idmt'],$value['ten_mt'],$value['gia']);
			
		$mangsplist[]=$sp;
		
	}

	return $mangsplist;
}

	
public function viewAllproduct($idsp){
	//hien tat ca san pham

	$sql="select * from maytinh where idmt=$idsp";

		
	$this->model->select($sql);

		
	$a_data2=$this->model->fetchArray();

		
	$mangsp=array();

	
	foreach ($a_data2 as $row) {	
		$cart2=new giohang($idsp,$row['ten_mt'],$row['gia']);
			
		$mangsp[]=$cart2;
	}

	return $mangsp;
}

	
public function addCart($id_sp){
	
	$mangCart=array();
		
	$mangCart=$this->viewAllproduct($id_sp);

	$idchonsp=$mangCart[0]->idmt;

	$cart=new giohang($idchonsp,$mangCart[0]->ten_mt,$mangCart[0]->gia);


	if($_SESSION['cart'][$idchonsp]){
		$_SESSION['cart'][$idchonsp]->soluong=+1;	
	}

	else{

		
		$_SESSION['cart'][$idchonsp]=$cart;

			
		$_SESSION['cart'][$idchonsp]->soluong=1;

		
	}

	
}

	
	public function xoaCart($pid){
		unset($_SESSION['cart'][$pid]);
	}
	public function capnhatCart(){
		foreach ($_POST['soluong'] as $idmt => $soluong) {
				if ($soluong==0){
					unset($_SESSION['cart'][$idmt]);
				}

			
			else{
				 $_SESSION['cart'][$idmt]->soluong = $soluong;

			}

			
		}

	} 
}

	
?>

- Chú ý 3 file trên đặt vào thư mực controller nhé

TIếu tục file model nhé các bạn

Đây là file thực thị các câu truy vấn dữ liệu khi mà controllers yêu cầu một câu truy vấn nào thì ta tiến hàng thực thi câu truy vấn đó.

Models

<?php
	
class model{
private $connection;
private $localhost;
private $username;
private $password;
private $database;
private $result;
private $queryResult=null;
public function __construct(){
include_once 'config/dbcon.php';
	$this->localhost=$db_localhost;
	$this->username=$db_username;
	$this->password=$db_password;
	$this->database=$db_database;
	$this->connect();
}

	
public function connect(){
	$this->connection=mysql_connect($this->localhost,$this->username,$this->password) or die('kết nối không thành công');
	
	if(isset($this->connection)){	
		mysql_select_db($this->database,$this->connection);	
		mysql_query("set names 'UTF8'");	
	}
	else{	
		echo "kết nối không thành công";	
	}

}

	
public function select($sql){
	$this->result=mysql_query($sql,$this->connection);
	return $this->result; 
}

public function count_record(){	
	return mysql_num_rows($this->result);	
}
public function fetchArray($queryResult=NUll){
	
	if($queryResult==NULL){
		if(is_resource($this->result))
		{

			$mangArray=array();
			while($row=mysql_fetch_array($this->result)){
				$mangArray[]=$row;
			}
		return $mangArray;
		}	
	}
}

public function insert_cart($arrayDulieu){

 }
}
?>

các bạn tạo 2 file mà đầu bài mình cũng ghi:file cart-template.php và file viewCart-template.php dùng để đưa dữ liệu sản phẩm ra.

Views

//tạo file cart-template.php đưa thông tin sản phâm ra
<table border='1'>
	<tr>
		<td>TÊN SP</td>
		<td>GIÁ</td>
		<td>MUA SP</td>
	</tr>
	<?php
	$cart_sp=new cart();
	$manglist_sp=$cart_sp->viewAllsanpham();
	foreach ($manglist_sp as $value) {
	?>
		<tr>
		<td><?php echo $value->ten_mt;?></td>
		<td><?php echo $value->gia;?></td>
		<td>
		<?php echo "<p><input type='submit' value='Mua' onclick=\"window.location='".$_SERVER['PHP_SELF']."?addcart=$value->idmt'\"></input>";?>
		</td>
			
		</tr>

		
	<?php }?>
</table>

- Tiếp các bạn tạo file viewCart-template.php

<center>
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
    <table cellspacing='0' border="1" style="text-align: center">
    <tr>
        <th>Tên sp</th>
        <th>Giá</th>
        <th>Số lượng</th>
        <th>Tổng giá</th>
        <th>Xóa</th>
    </tr>
    <?php
    $total = 0;
 if(isset($_SESSION['cart'])){
    foreach ($_SESSION['cart'] as $value) {
        ?>

        <tr>
       <td><?php echo $value->ten_mt;?></td>
       
       <td><?php echo $value->gia;?>đ</td>
       <td><input type='text' name='soluong[<?php echo $value->idmt;?>]' id='soluong' value='<?php echo $value->soluong;?>' /></td>
       <td><?php echo number_format($value->gia*$value->soluong,3);?>000 đ</td>
       <td><a href='<?php echo $_SERVER['PHP_SELF']."?xoa=".$value->idmt;?>'>Xóa</a></td>
       </tr>

       <?php 
        $tong = number_format($value->soluong*$value->gia,3);
        $total += $tong;
    }//dong foreach
}
?>
    <tr>
    <td colspan="4"><strong>Tổng tiền: <?php echo number_format($total,3);?>.000 đ</strong></td>
    <td><a href='<?php echo $_SERVER['PHP_SELF']."?xoahet";?>'>Xóa hết</a></td>
    </tr>
     
    
</table>
    <?php
    echo "<a href='".$_SERVER['PHP_SELF']."'>Quay lại mua hàng</a>";
    echo "<input type='submit' name='update' value='Cập Nhật Giỏ Hàng' />";
    ?>
    </form>
</center>

Chúc các bạn thực hiện thành công nhé smiley

 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)